简体   繁体   中英

mongodb group aggregation pipeline include objectId (_id)

I have a pipeline in mongodb below.

pipeline.push({ $project: { 'name1': 1, isGroup: { $cond: [{ $eq: ['$name2', '']}, false, true]}, onlyGroup: 1, 'objecttype':1 } })
pipeline.push({ $group: { _id:  { 'name1': '$name1', isGroup: '$isGroup', onlyGroup: '$onlyGroup', 'objecttype': '$objecttype'} } })
pipeline.push({ $sort: { _id: 1 } })
pipeline.push({ $project: {  'name1': '$_id.name1', isGroup: '$_id.isGroup', 'objecttype': '$_id.objecttype',  onlyGroup: '$_id.onlyGroup' } })
break;

As you can see, the output is name1, isGroup, objecttype, onlyGroup.

I would like to add _id as one of the output too. How do I make it happen?

_id is included but it had to be brought inside group otherwise after group, everything not included in group gets excluded.

So here is what got this issue fixed for me. Since I had to get some other fields too, the solution below worked perfectly.

pipeline.push({ $project: { 'name1': 1, isGroup: { $cond: [{ $eq: ['$name2', '']}, false, true]}, onlyGroup: 1, 'objecttype':1, idd:'$_id' } })

pipeline.push({ $group: { _id: { 'name1': '$name1', isGroup: '$isGroup', onlyGroup: '$onlyGroup' }, objecttype: { $push: '$objecttype' }, idd:{ $push: '$idd' } } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM