【问题标题】:$nin with the $expr$nin 与 $expr
【发布时间】:2019-05-04 20:01:06
【问题描述】:

我有一个查询要查找用户 CreatedBy 是否在 SharedWith 中。我想反转查询以检查CreatedBy 是否不在SharedWith 中。

[
    {
        "$match": {
            "$and": [
                {
                    "$and": [
                        {
                            "SharedWith": {
                                "$exists": true
                            }
                        },
                        {
                            "$expr": {
                                "$in": [
                                    "$CreatedBy",
                                    "$Multi_User"
                                ]
                            }
                        }
                    ]
                }
            ]
        }
    }
]

MongoDB 不支持直接使用 $nin$not 进行 $and 查询。

知道如何实现这一点。

用户文档如下所示,

   Collection = [
        {"CreatedBy":
             {"_id": "User001",
              "Email": "user@eg.com",
              "Name": "User001"},
         "SharedWith": [
             {"_id": "User001",
              "Email": "user@eg.com",
              "Name": "User001"},
             {"_id": "User002",
              "Email": "user@eg.com",
              "Name": "User002"},
             {"_id": "User003",
              "Email": "user@eg.com",
              "Name": "User003"},
         ]}

    ]

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework pymongo


    【解决方案1】:

    $nin 是查询运算符而不是聚合运算符,并且 $expr 仅支持 aggregation 运算符而不支持 query 运算符。因此,您可能应该使用 $not $in$expr 表达式 以这种方式

    {
      "$match": {
        "$and": [
          {
            "$or": [
              {
                "Multi_User": {
                  "$exists": False
                }
              },
              {
                "$expr": {
                  "$not": { "$in": ["$CreatedBy", "$Multi_User"] }
                }
              }
            ]
          }
        ]
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多