为什么$ setIntersection失败,如果数组是子文档的阵列,而不是收集在一个领域? [英] Why $setIntersection failed if arrays are array of subdocuments and not a field in the collection?

查看:136
本文介绍了为什么$ setIntersection失败,如果数组是子文档的阵列,而不是收集在一个领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下文件:

{
    "item1" : [
        {
            "a" : 1,
            "b" : 2
        }
    ],
    "item2" : [ "a", "b" ]
}

下面的查询:

db.test.aggregate([ 
    { "$project": { "items": { "$setIntersection": [ "$item1", "$item2" ] } }}
])

返回预期的结果:

returns the expected result:

{ "_id" : ObjectId("5710785387756a4a75cbe0d1"), "a" : [ ] }

如果该文件是这样的:

{ "item2" : [ "a", "b" ] }

然后:

db.test.aggregate([ { "$project": { 
    "a": { "$setIntersection": [ "$item2", [ "a" ] ] } } } 
])

收益率:

{ "_id" : ObjectId("5710785387756a4a75cbe0d1"), "a" : [ "a" ] }

db.test.aggregate([         
    { "$project": { "items": { "$setIntersection": [ "$item2", [ { "a" : 1, "b" : 2 } ] ] } } } 
])

与失败:

ERRMSG:字段包含不允许$ EX pressions内

"errmsg" : "field inclusion is not allowed inside of $expressions"

db.test.aggregate([ { "$project": { 
    "items": { "$setIntersection": [ "$item2", [ { "a": "b" } ] ] } } } 
])

与失败:

ERRMSG:FieldPath会'B'不以$开头

"errmsg" : "FieldPath 'b' doesn't start with $"

,使这项工作的唯一方法是使用 $文字运营商。

The only way to make this work is to use the $literal operator.

为什么要使用 $文字 运营商如果 $ setIntersection 参数是子文档的阵列,而不是一个字段文件中?

Why should we use the $literal operator if $setIntersection arguments are array of sub-documents and not a field in the document?

推荐答案

这似乎是在MongoDB中3.2兼容的变化因而作为<一提到预期的行为href=\"https://docs.mongodb.org/manual/release-notes/3.2-compatibility/#aggregation-compatibility-changes\"相对=nofollow>聚集变化兼容性MongoDB中的3.2 :

This appears to be a compatibility changes in MongoDB 3.2 thus is the expected behavior as mentioned in the Aggregation Compatibility Changes in MongoDB 3.2:

数组元素不再视为聚合管道文字。相反,数组的每个元素现在被解析为一个前pression。为了治疗元素为文字而不是前pression,使用的 $文字 操作符来创建一个文本值。

Array elements are no longer treated as literals in the aggregation pipeline. Instead, each element of an array is now parsed as an expression. To treat the element as a literal instead of an expression, use the $literal operator to create a literal value.

这篇关于为什么$ setIntersection失败,如果数组是子文档的阵列,而不是收集在一个领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆