我有一个文档的集合设置,如下所示:
{
"_id" : ObjectId("5c786d9486c1140b1452d777"),
"code" : "TEST-123",
"owner" : "John",
"cars" : [
{
"carPlate" : "QPZ-756",
"carColor" : "blue"
},
{
"carPlate" : "REF-473",
"carColor" : "red"
}
],
}我正在寻找一个mongo聚合查询,该查询获取每个carPlate并为集合中的每个文档输出以下内容
{
"carPlate" : "QPZ-756",
"owner" : "John",
"code" : "TEST-123",
},
{
"carPlate" : "REF-473",
"owner" : "John",
"code" : "TEST-123",
},我看了一下$map操作符,这是一个很好的起点吗?
发布于 2019-03-01 09:30:11
我将使用$unwind来扁平化数组,然后使用$mergeObjects来组合键和$replaceRoot,以将合并文档提升到顶部。
就像这样
db.colname.aggregate([
{$unwind:"$cars"},
{$replaceRoot:{newRoot:{$mergeObjects:[{owner:"$owner"}, "$cars"]}}}
])https://stackoverflow.com/questions/54936561
复制相似问题