MongoDB aggregation projection on collection -
i have collection full of documents this.
{ "_id" : objectid("5696db8a049c1bb2ecaaa10f"), "resultsets" : [ { "headers" : [ "a", "b" ], "data" : [ [ 0, 1 ] ] }, { "headers" : [ "c", "d" ], "data" : [ [ 2, 3 ] ] } ] }
i use aggregation project document just.
{ c: 2, d: 3 }
just wondering best way be.
if using mongodb 3.2 $arrayelemat
go long way in getting desired aggregation output dealing arrays.
run following aggregation pipeline, uses $arrayelemat
operator return desired values in new keys:
var pipeline = [ { "$match": { "resultsets.headers": { "$in": [ "c", "d" ] } } }, { "$unwind": "$resultsets" }, { "$match": { "resultsets.headers": { "$in": [ "c", "d" ] } } }, { "$project": { "_id": 0, "c": { "$arrayelemat": [ "$resultsets.data", 0 ] }, "d": { "$arrayelemat": [ "$resultsets.data", 1 ] } } } ] db.collection.aggregate(pipeline);
Comments
Post a Comment