user1987630
user1987630

Reputation:

How do i perform this routine in MongoDB?

Have a collection with each document like

{ 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' } }

Want to have something like this in place of the above

{ uid: 12, content: { id: [2, 3] } }
{ uid: 34, content: { id: [1, 4] } }

Suggest with ways to go by this. Thank you.

Upvotes: 0

Views: 345

Answers (2)

Tamil Selvan C
Tamil Selvan C

Reputation: 20229

Use Mongo Aggregation

Try

db.tbl_name.aggregate( {$group: { uid: "$id", content: {$push: "$id"} } } )

Upvotes: 0

Vishwas
Vishwas

Reputation: 7067

Use Mongo Aggregation to get expected output

If you are using mongoID '_id' to group then use

db.collection.aggregate({"$group":{"_id":"$user.uid","user_id":{"$push":"$_id"}}},
{$project:{"uid":"$_id","content":"$user_id","_id":0}})

If you want to use your own id to group then use (you just need to specify key in push)

 db.collection.aggregate({"$group":{"_id":"$user.uid","user_id":{"$push":"$id"}}},
{$project:{"uid":"$_id","content":"$user_id","_id":0}})

Upvotes: 1

Related Questions