【问题标题】:MongoDB - $setIsSubset operator not working with $match stageMongoDB - $setIsSubset 运算符不适用于 $match 阶段
【发布时间】:2018-06-19 04:00:59
【问题描述】:

我构造了一个这样的查询:

db.test.aggregate([{$match: {$setIsSubset: [['hello', 'you'], '$words']}}])

我想返回字段 'words' 的数组包含字符串 ['hello', 'you'] 的所有文档。

执行这个查询我得到这个错误:

"errmsg" : "未知顶级运算符:$setIsSubset"

我做错了什么?

感谢您的帮助!

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    如果你想在$match 中使用$setIsSubset(这是一个表达式),你应该使用$expr

    db.test.aggregate([
        {
            $match: {
                $expr: {
                    $setIsSubset: [["hello", "you"], "$words"]}
                }
            }
    ])
    

    对于低于 3.6 的 MongoDB 版本,您可以使用 $redact:

    db.test.aggregate([
        {
            $redact: {
                $cond: {
                    if: { $eq: [ { $setIsSubset: [["hello", "you"], "$words"]}, true ] },
                    then: "$$KEEP",
                    else: "$$PRUNE"
                }
            }
        }
    ])
    

    【讨论】:

    • 我得到同样的错误,但 $expr:"errmsg" : "unknown top level operator: $expr"
    • @BetterSaveThan对不起,您必须使用低于 3.6 的 MongoDB。在这种情况下,您可以尝试使用$redact,就像我编辑的答案一样
    【解决方案2】:

    这行得通:

     db.test.aggregate([{$match: {'words': {'$all': ["hello", "you"] }}}])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 2017-08-03
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 2016-12-04
      相关资源
      最近更新 更多