如何从此文档集合中传递
/* 1 */
{
"F" : [
{
"n" : "test1",
"v" : "value1"
},
{
"n" : "test2",
"v" : "value2"
}
],
"POR" : [
{
"n" : "1test1",
"v" : "1value1"
},
{
"n" : "1test2",
"v" : "1value2"
},
{
"n" : "1test3",
"v" : "1value3"
}
]
}
/* 2 */
{
"F" : [
{
"n" : "2test1",
"v" : "2value1"
},
{
"n" : "2test2",
"v" : "2value2"
}
],
"POR" : [
{
"n" : "2test1",
"v" : "2value1"
},
{
"n" : "2test2",
"v" : "2value2"
}
]
}
/* 3 */
{
"F" : [
{
"n" : "3test1",
"v" : "3value1"
},
{
"n" : "3test2",
"v" : "3value2"
}
],
"POR" : [
{
"n" : "3test1",
"v" : "3value1"
}
]
}
到此:
{
"ITEMS": [
{ "n": "2test1", "v": "2value1" },
{ "n": "2test2", "v": "2value2" },
{ "n": "1test1", "v": "1value1" },
{ "n": "1test2", "v": "1value2" },
{ "n": "1test3", "v": "1value3" },
{ "n": "3test1", "v": "3value1" }
]
}
我想从多个文档中提取子数组元素,但我找不到方法/方法。
尝试了第一种方法:
db.test.aggregate( [ { $unwind : "$POR" } ] ).pretty();
答案 0 :(得分:1)
我认为这可以满足您的需求:
> db.uwnd.aggregate([
{$unwind:"$F"},
{$unwind:"$POR"},
{$group:{_id:null,items:{$addToSet:"$F",$addToSet:"$POR"}}}
]).pretty()
鉴于上述数据,这将返回以下文件:
{
"_id" : null,
"items" : [
{
"n" : "1test3",
"v" : "1value3"
},
{
"n" : "1test1",
"v" : "1value1"
},
{
"n" : "1test2",
"v" : "1value2"
},
{
"n" : "2test1",
"v" : "2value1"
},
{
"n" : "2test2",
"v" : "2value2"
},
{
"n" : "3test1",
"v" : "3value1"
}
]
}
因此,查询展开两个数组,然后对数据进行分组,将条目添加到"F"
和"POR"
对象的新项目数组