我有一个名为offer的集合,下面是一个示例文档,
offerId
我希望按[
{
"offerId": "e6c1f140-6407-4481-9a18-56789d90f549",
"outlet": [
{
"storeUuid": "bf71e102-9da1-47b5-81e1-98d27f20bcf4",
"location": {
"type": "Point",
"coordinates": [
77,
22
]
}
},
{
"storeUuid": "09d6fc18-9d5c-4b4f-8de1-c6f555b8a370",
"location": {
"type": "Point",
"coordinates": [
77,
22
]
}
},
{
"storeUuid": "b3cdd08d-f7f5-4544-8279-08489974148c",
"location": {
"type": "Point",
"coordinates": [
77,
22
]
}
}
],
"startTime": "2018-04-05T12:30:37.954Z",
"endTime": "2018-04-08T12:38:00.046Z"
},
{
"offerId": "3a06d230-5836-44c2-896b-f5bfb6b27a77",
"outlet": [
{
"storeUuid": "f18a9a9e-539e-4a9e-b313-d947e2ce76de",
"location": {
"type": "Point",
"coordinates": [
77,
22
]
}
},
{
"storeUuid": "b3da5136-15a4-4593-aabd-4788f7d80f19",
"location": {
"type": "Point",
"coordinates": [
77,
22
]
}
}
],
"startTime": "2018-04-06T08:03:37.954Z",
"endTime": "2018-04-07T07:35:00.046Z"
}
]
进行分组,结果应为
db.offers.aggregate([
{
$group: {
_id: "$offerId",
outlet: {
$addToSet: "$outlets"
}
}
}
])
到目前为止我的聚合查询
float ()
任何帮助将不胜感激
答案 0 :(得分:1)
这样做
添加所需字段的投影。
按所需字段分组
创建一个新属性并将其推送到嵌套字段
db.getCollection('offers').aggregate([
{ $project : { offerId : 1 , outlets : 1, startTime: 1, endTime: 1 } },
{ $group: {
_id: "$offerId" ,
outlet: {
$push: {
storeUuid : "$outlets.storeUuid",
location: "$outlets.location"
}
},
startTime: { "$first": "$startTime"},
endTime: { "$first": "$endTime"}
}
}
])
答案 1 :(得分:0)
$ addToSet:返回由此产生的所有唯一值的数组 将表达式应用于一组文档中的每个文档 按键共享同一组。输出数组中元素的顺序 没有具体说明。可以用于
$ push:返回应用a产生的所有值的数组 表达共享的一组文档中的每个文档 按键分组。
在您的情况下,需要$ push运算符:
db.offers.aggregate([
{$unwind:'$outlets'},
{$group:{_id:'$offerId',outlets:{$push:'$outlets'}}}
])
更多: https://docs.mongodb.com/manual/reference/operator/aggregation/push/#grp._S_push https://docs.mongodb.com/manual/reference/operator/aggregation/addToSet/
有关聚合管道运算符的完整列表
https://docs.mongodb.com/manual/reference/operator/aggregation/