mongodb - Combining multiple sub-documents into a new doc in mongo -
i trying query multiple sub-documents in mongodb , return single doc. think aggregation framework way go, but, can't see right.
take following docs:
{ "board_id": "1", "hosts": [{ "name": "bob", "ip": "10.1.2.3" }, { "name": "tom", "ip": "10.1.2.4" }] } { "board_id": "2", "hosts": [{ "name": "mickey", "ip": "10.2.2.3" }, { "name": "mouse", "ip": "10.2.2.4" }] } { "board_id": "3", "hosts": [{ "name": "pavel", "ip": "10.3.2.3" }, { "name": "kenrick", "ip": "10.3.2.4" }] }
trying query result this:
{ "hosts": [{ "name": "bob", "ip": "10.1.2.3" }, { "name": "tom", "ip": "10.1.2.4" }, { "name": "mickey", "ip": "10.2.2.3" }, { "name": "mouse", "ip": "10.2.2.4" }, { "name": "pavel", "ip": "10.3.2.3" }, { "name": "kenrick", "ip": "10.3.2.4" }] }
i've tried this:
db.collection.aggregate([ { $unwind: '$hosts' }, { $project : { name: 1, hosts: 1, _id: 0 }} ])
but it's not quite want.
you can aggregate. let's assume data in collection named board, please replace whatever collection name is.
db.board.aggregate([ {$unwind:"$hosts"}, {$group:{_id:null, hosts:{$addtoset:"$hosts"}}}, {$project:{_id:0, hosts:1}} ]).pretty()
it return
{ "hosts" : [ { "name" : "kenrick", "ip" : "10.3.2.4" }, { "name" : "pavel", "ip" : "10.3.2.3" }, { "name" : "mouse", "ip" : "10.2.2.4" }, { "name" : "mickey", "ip" : "10.2.2.3" }, { "name" : "tom", "ip" : "10.1.2.4" }, { "name" : "bob", "ip" : "10.1.2.3" } ] }
Comments
Post a Comment