我如何在 MongoDB 中执行此例程?
How do i perform this routine in MongoDB?
每个文档都有一个集合,例如
{ id: 1, user: { uid: 34, name: 'SDSDSD' } }
{ id: 2, user: { uid: 12, name: 'FHGJDF' } }
{ id: 3, user: { uid: 12, name: 'FHGJDF' } }
{ id: 4, user: { uid: 34, name: 'SDSDSD' } }
想用这样的东西代替上面的东西
{ uid: 12, content: { id: [2, 3] } }
{ uid: 34, content: { id: [1, 4] } }
提出解决方法。谢谢。
使用Mongo Aggregation获得预期输出
如果您使用 mongoID '_id' 进行分组,则使用
db.collection.aggregate({"$group":{"_id":"$user.uid","user_id":{"$push":"$_id"}}},
{$project:{"uid":"$_id","content":"$user_id","_id":0}})
如果你想使用自己的id
来分组然后使用(你只需要在push中指定key)
db.collection.aggregate({"$group":{"_id":"$user.uid","user_id":{"$push":"$id"}}},
{$project:{"uid":"$_id","content":"$user_id","_id":0}})
尝试
db.tbl_name.aggregate( {$group: { uid: "$id", content: {$push: "$id"} } } )
每个文档都有一个集合,例如
{ id: 1, user: { uid: 34, name: 'SDSDSD' } }
{ id: 2, user: { uid: 12, name: 'FHGJDF' } }
{ id: 3, user: { uid: 12, name: 'FHGJDF' } }
{ id: 4, user: { uid: 34, name: 'SDSDSD' } }
想用这样的东西代替上面的东西
{ uid: 12, content: { id: [2, 3] } }
{ uid: 34, content: { id: [1, 4] } }
提出解决方法。谢谢。
使用Mongo Aggregation获得预期输出
如果您使用 mongoID '_id' 进行分组,则使用
db.collection.aggregate({"$group":{"_id":"$user.uid","user_id":{"$push":"$_id"}}},
{$project:{"uid":"$_id","content":"$user_id","_id":0}})
如果你想使用自己的id
来分组然后使用(你只需要在push中指定key)
db.collection.aggregate({"$group":{"_id":"$user.uid","user_id":{"$push":"$id"}}},
{$project:{"uid":"$_id","content":"$user_id","_id":0}})
尝试
db.tbl_name.aggregate( {$group: { uid: "$id", content: {$push: "$id"} } } )