mongoShell查询返回的文件为零,用于比较同一文档中的列

时间:2018-05-04 06:57:12

标签: mongodb mongodb-query

我有类似数据结构的集合

{
   id: 1
   limit: {
        max: 10000,
        used: 0     
   }
}

我尝试运行以下查询但是它给出了0结果

db.getCollection('promos').aggregate(
[
{ $match: { id:  1} },
{$match: { $expr: {$gt ["limit.max" , "limit.used"]}}}

])

我还使用了以下查询

db.getCollection('promos').aggregate(
[
{ $match: { id:  1} },
{$match: { "$limit.max": {$gt: "limit.used"}}}

])

他们都没有给出结果。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您需要在$前加上“字段表达式”。这也可以在.find()

中完成
db.getCollection('promos').find({
  "id": 1,
  "$expr": { "$gt": [ "$limit.max" , "$limit.used" ] }
})

如果您确实需要使用聚合,则可以使用单个$match阶段:

db.getCollection('promos').aggregate([
  { "$match": {
    "id": 1,
    "$expr": { "$gt": [ "$limit.max" , "$limit.used" ] }
  }}
])

这就是$expr的工作方式,您可以在同一查询或管道阶段将其与其他常规查询运算符“混合”。

另请参阅$gt了解一般用法示例

当然,如果您实际上甚至没有MongoDB 3.6,那么您使用$redact代替:

db.getCollection('promos').aggregate([
  { "$match": { "id": 1 } },
  { "$redact": {
    "$cond": {
      "if": { "$gt": [ "$limit.max" , "$limit.used" ] },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }}
])

或使用$where。适用于所有版本:

db.getCollection('promos').find({
  "id": 1,
  "$where": "this.limit.max > this.limit.used"
})
相关问题