$ setIntersection失败,其中包含不在集合中的子文档数组 [英] $setIntersection failed with array of subdocuments that are not in the collection
问题描述
请考虑以下文档:
{
"item1" : [
{
"a" : 1,
"b" : 2
}
],
"item2" : [ "a", "b" ]
}
以下查询:
db.test.aggregate([
{ "$project": { "items": { "$setIntersection": [ "$item1", "$item2" ] } }}
])
返回预期结果:
{ "_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":在$ expressions内不允许包含字段"
"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 $"
完成这项工作的唯一方法是使用$literal
运算符.
The only way to make this work is to use the $literal
operator.
为什么<<我们为什么要使用 $literal
运算符href ="https://docs.mongodb.org/manual/reference/operator/aggregation/setIntersection/" rel ="nofollow"> $setIntersection
参数是子文档数组,而不是文档中的字段?
推荐答案
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:
数组元素在聚合管道中不再被视为文字.取而代之的是,现在将数组的每个元素解析为一个表达式.要将元素视为文字而不是表达式,请使用
$literal
运算符以创建文字值.
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屋!