2017-10-11 73 views
0

考虑下面两个文件:组数组元素计数出现

{ "name" : "test1", "source" : ["Apple","Cherry"], "dest" : ["Banana", "Durian"]} 
{ "name" : "test2", "source" : ["Melon","Fig"], "dest" : ["Apple"]}] 

输入

["Apple","Orange","Fig"] 

期望输出

{ "_id" : "Apple", nameList : ["test1", "test2"] } 
{ "_id" : "Fig", nameList : ["test2"] } 
{ "_id" : "Orange", nameList : [] } 

聚合

db.getCollection<name>.aggregate([ 
    { "$match" : <some_matching_conditions>}, 
    { "$project" : 
      { "$project" : { "input_array" : { "$literal" : ["Apple","Orange","Fig"]} }}, 
      { "obj" : {"$setUnion" : ["$source", "$dest"]}}, 
    }, 
    { "$unwind" : "$aray"}, 
    { "$match" : { "aray" : { "$in" : "$obj"}}}, 
    { "$group" : <grouping_conditons>} 
]) 
+0

错误:“errmsg”:“异常:错误查询:BadValue $ in需要数组” – Bala

回答

0

你可以尝试下面的聚合。

db.collection_name.aggregate([ 
    { 
    "$project": { 
     "name": 1, 
     "farray": { 
     "$setIntersection": [ 
      { 
      "$concatArrays": [ 
       "$source", 
       "$dest" 
      ] 
      }, 
      input_array 
     ] 
     } 
    } 
    }, 
    { 
    "$unwind":"$farray" 
    }, 
    { 
    "$group": { 
     "_id": "$farray", 
     "namelist": { 
     "$push": "$name" 
     } 
    } 
    } 
])