如果满足条件查询,MongoDB返回true

时间:2018-01-15 11:50:45

标签: mongodb

我想在伪代码中编写一个类似的查询:return true if value X is greater than value Y。为了在数据中设置一个返回true或false的字段。像这样: { xIsGreaterThanY: true, randomData: 123456, moreRandom: abcdefg}

但我不知道如何编写这种类型的查询,因为我对MongoDB很新。这甚至可能实现吗?

我当然可以获取所有数据并在JS中进行计算,但我想知道它是否可行,这样我就可以了解更多有关MongoDB及其所有魔法的信息。此外,当数据从数据库返回时,尽可能准备好数据是非常好的。

1 个答案:

答案 0 :(得分:1)

让我们从获取一些值开始;

> 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 }