如果满足条件查询,MongoDB返回true
我想在伪代码中编写一个类似这样的查询:如果满足条件查询,MongoDB返回true,mongodb,Mongodb,我想在伪代码中编写一个类似这样的查询:如果值X大于值Y,则返回true。以便将返回的数据中的字段设置为true或false。像这样: {xisgreeterthany:true,randomData:123456,moreRandom:abcdefg} 但我不知道如何编写这种类型的查询,因为我对MongoDB相当陌生。这有可能实现吗 我当然可以得到所有的数据,然后用JS或其他什么东西进行计算,但我想知道这是否可行,这样我就可以了解更多关于MongoDB及其魔力的信息。另外,当数据从数据库返回时,
如果值X大于值Y,则返回true
。以便将返回的数据中的字段设置为true或false。像这样:
{xisgreeterthany:true,randomData:123456,moreRandom:abcdefg}
但我不知道如何编写这种类型的查询,因为我对MongoDB相当陌生。这有可能实现吗
我当然可以得到所有的数据,然后用JS或其他什么东西进行计算,但我想知道这是否可行,这样我就可以了解更多关于MongoDB及其魔力的信息。另外,当数据从数据库返回时,尽可能地准备好数据也是非常好的
> for(var i = 1; i <= 10; i++) { db.test.save({a : i, b: 10-i}); }
WriteResult({ "nInserted" : 1 })
> db.test.find()
{ "_id" : ObjectId("5a5c997b28e6f31805330889"), "a" : 1, "b" : 9 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088a"), "a" : 2, "b" : 8 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088b"), "a" : 3, "b" : 7 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088c"), "a" : 4, "b" : 6 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088d"), "a" : 5, "b" : 5 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088e"), "a" : 6, "b" : 4 }
{ "_id" : ObjectId("5a5c997b28e6f3180533088f"), "a" : 7, "b" : 3 }
{ "_id" : ObjectId("5a5c997b28e6f31805330890"), "a" : 8, "b" : 2 }
{ "_id" : ObjectId("5a5c997b28e6f31805330891"), "a" : 9, "b" : 1 }
{ "_id" : ObjectId("5a5c997b28e6f31805330892"), "a" : 10, "b" : 0 }
使用$cond-查看
> db.test.aggregate([
... { $project: { aGreaterThanb: { $cond: { if: { $gt: [ "$a", "$b" ] }, then: true, else: false } } } }
...
... ]);
{ "_id" : ObjectId("5a5c997b28e6f31805330889"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088a"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088b"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088c"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088d"), "aGreaterThanb" : false }
{ "_id" : ObjectId("5a5c997b28e6f3180533088e"), "aGreaterThanb" : true }
{ "_id" : ObjectId("5a5c997b28e6f3180533088f"), "aGreaterThanb" : true }
{ "_id" : ObjectId("5a5c997b28e6f31805330890"), "aGreaterThanb" : true }
{ "_id" : ObjectId("5a5c997b28e6f31805330891"), "aGreaterThanb" : true }
{ "_id" : ObjectId("5a5c997b28e6f31805330892"), "aGreaterThanb" : true }