mongodb - Create unique array from two or more documents -
mongodb - Create unique array from two or more documents -
i have collection this
class="lang-js prettyprint-override"> { "_id" : objectid("53a7fb486201281a1f698fe4"), "userid" : objectid("53a7fade6201281a1f698fd9"), "magic" : [ { "power" : 0, "mana" : 10, "foo" : null, "bar" : 150 }, { "power" : 2, "mana" : 2, "foo" : 200, "bar" : 1 }, ] } { "_id" : objectid("53a7fb486201281a1f698fe4"), "userid" : objectid("53a7fade6201281a1f698fd9"), "magic" : [ { "power" : 20, "mana" : 210, "foo" : null, "bar" : 2150 }, { "power" : 23, "mana" : 23, "foo" : 2004, "bar" : 14 }, ] } { "_id" : objectid("53a7fb486201281a1f698fe4"), "userid" : objectid("anotherid"), "magic" : [ { "power" : 20, "mana" : 210, "foo" : null, "bar" : 2150 }, { "power" : 23, "mana" : 23, "foo" : 2004, "bar" : 14 }, ] } i want create unique array "magic of userid objectid("53a7fade6201281a1f698fd9")
i did seek this
class="lang-js prettyprint-override">db.mycoll.aggregate([ { '$group': { _id: { magic: "$magic", }, "allmagic": { $push: "$magic" }, }, } ]); the result รจ array of array of magic of collection mycoll seek utilize $match
db.mycoll.aggregate([ { '$group': { _id: { magic: "$magic", }, "allmagic": { $push: "$magic" }, }, $match : { "userid" : objectid("53a7fade6201281a1f698fd9") } } ]); but have error exception: pipeline stage specification object must contain 1 field.. want utilize in node.js (i utilize mongoose well)
working arrays in aggregation framework , across documents want utilize $unwind operator:
db.mycoll.aggregate([ // match documents user id first { "$match": { "userid": objectid("53a7fade6201281a1f698fd9") }}, // unwind array { "$unwind": "$magic" }, // grouping single user document { "$group": { "_id": "$userid", "magic": { "$addtoset": "$magic" } }} ]) the $addtoset operator keeps elements of array "unique", if want combine without removing duplicates utilize $push instead.
mongodb aggregation-framework
Comments
Post a Comment