考慮下面的文檔中的子文檔的數組:
{
"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」: 「字段包含不允許$表達式的內部」
和:
db.test.aggregate([ { "$project": {
"items": { "$setIntersection": [ "$item2", [ { "a": "b" } ] ] } } }
])
失敗:
「ERRMSG」:「FieldPath會 'B'不以$開頭「
使這項工作的唯一方法是使用$literal
運營商。
我們爲什麼要使用$literal
運營商如果$setIntersection
參數是在文檔中的子文檔的陣列,而不是一個場?