首页 > 解决方案 > 如果第三个键为真,则比较 mongodb 文档的两个键

问题描述

我有这样的文件,我正在使用 mongo 3.6 和聚合。

[
   {
      id: 123,
      isLimit: "YES",
      maxUserCanComment: 10,
      commentCount: 6 
   },
   {
      id: 124,
      isLimit: "NO",
      maxUserCanComment: 0,
      commentCount: 3 
   },
   {
      id: 125,
      isLimit: "YES",
      maxUserCanComment: 3,
      commentCount: 5 
   }
]

我需要那个文件,如果 isLimit == "NO" 拿它,如果 isLimit == "YES",首先检查commentCount < maxUserCanComment。我试过这个

[
   $expr: { $gt: ["$commentCount", "$maxUserCanComment"] } // and also tried to add ithis in $cond
]

标签: node.jsmongodbmongodb-query

解决方案


您需要在$or此处使用查询运算符,然后您可以$expr在其中使用。

db.collection.find({
  "$or": [
    { "isLimit": "NO" },
    {
      "isLimit": "YES",
      "$expr": {
        "$gt": [
          "$commentCount",
          "$maxUserCanComment"
        ]
      }
    }
  ]
})

Mongo游乐场


推荐阅读