【问题标题】:Comparing two fields in MongoDb比较 MongoDb 中的两个字段
【发布时间】:2019-03-18 15:39:10
【问题描述】:

我是 MongoDB 新手,正在尝试比较 MongoDB 集合中的 2 个字段。

字段是属性(对象)和集合(数组)

{ 
    "_id" : ObjectId("55ae1e47309ffcbd1b67bd6c"), 
    "collections" : [
        {
            "collection_code" : "9TEST", 
            "_id" : ObjectId("5c76eee4bb4afe3a3603eeb3")
        }
    ], 
   "attributes" : {
        "collection_code" : "9TEST"
    }
}

我的查询是

db.companies.find({ $where : "this.attributes.collection_code == this.collections[collection_code]" })

遇到错误

{
    "message" : "TypeError: Cannot read property 'collection_code' of undefined" +
              "at _funcs1 (_funcs1:1:45) near 'on_code == this.collections[collection_co' ",
    "$err" : "TypeError: Cannot read property 'collection_code' of undefined" +
              "at _funcs1 (_funcs1:1:45) near 'on_code == this.collections[collection_co' ",
    "code" : 16722,
    "name" : "MongoError"
}

非常感谢任何帮助。提前致谢。

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    您需要$expr 来比较 MongoDB 中的两个字段。由于您有一个数组 (collection),并且您想检查是否有任何字段匹配的元素,您可以使用 $map$anyElementTrue 运算符,如下所示:

    db.col.find({
        $expr: {
            $anyElementTrue: {
                $map: {
                    input: "$collections",
                    in: {
                        $eq: [ "$$this.collection_code", "$attributes.collection_code" ]
                    }
                }
            }
        }
    })
    

    还有更简洁的方式,使用$in操作符

    db.col.find({
        $expr: {
            $in: [ "$attributes.collection_code", "$collections.collection_code" ]
        }
    })
    

    之所以有效,是因为collections.collection_code 在这种情况下代表一个字符串数组。

    编辑: 作为 3.0 版本的解决方法,您可以将 $anyElementTrue$redact 一起使用:

    db.col.aggregate([
        { $redact: {
            $cond: {
            if: {$anyElementTrue: { $map: { input: "$collections", as: "c", in: { $eq: [ "$$c.collection_code", "$attributes.collection_code" ]  }  }}},
            then: "$$KEEP",
            else: "$$PRUNE"
            }
        }
        }
    ])
    

    【讨论】:

    • 我们是否需要在 $expr 之前放置任何括号,因为我收到错误 - Can't canonicalize query: BadValue unknown top level operator: $expr
    • 你的 MongoDB 版本是什么?
    • 当前版本是 3.0.11
    • 3.0 不受支持。 3.2 不受支持。 3.4 即将不受支持。你真的应该考虑升级你的集群。
    • @PrithvirajMitra $expr 是在 3.6 中引入的,但我刚刚修改了我的答案,这个解决方法应该适合你
    猜你喜欢
    • 2022-01-22
    • 2013-08-09
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多