mongodb - Moongoose aggregate $match does not match id's -
i want show products ids (56e641d4864e5b780bb992c6 , 56e65504a323ee0812e511f2) , show price after subtracted discount if available.
i can count final price using aggregate, return document in collection, how make return matches ids
"_id" : objectid("56e641d4864e5b780bb992c6"), "title" : "keyboard", "discount" : numberint(10), "price" : numberint(1000) "_id" : objectid("56e65504a323ee0812e511f2"), "title" : "mouse", "discount" : numberint(0), "price" : numberint(1000) "_id" : objectid("56d90714a48d2eb40cc601a5"), "title" : "speaker", "discount" : numberint(10), "price" : numberint(1000) this query
productmodel.aggregate([ { $project: { title : 1, price: { $cond: { if: {$gt: ["$discount", 0]}, then: {$subtract: ["$price", {$divide: [{$multiply: ["$price", "$discount"]}, 100]}]}, else: "$price" } } } } ], function(err, docs){ if (err){ console.log(err) }else{ console.log(docs) } }) and if add $in query, returns empty array
productmodel.aggregate([ { $match: {_id: {$in: ids}} }, { $project: { title : 1, price: { $cond: { if: {$gt: ["$discount", 0]}, then: {$subtract: ["$price", {$divide: [{$multiply: ["$price", "$discount"]}, 100]}]}, else: "$price" } } } } ], function(err, docs){ if (err){ console.log(err) }else{ console.log(docs) } })
your ids variable constructed of "strings", , not objectid values.
mongoose "autocasts" string values objectid correct type in regular queries, does not happen in aggregation pipeline, in described in issue #1399.
instead must correct casting type manually:
ids = ids.map(function(el) { return mongoose.types.objectid(el) }) then can use them in pipeline stage:
{ "$match": { "_id": { "$in": ids } } } the reason because aggregation pipelines "typically" alter document structure, , therefore mongoose makes no presumption "schema" applies document in given pipeline stage.
it arguable "first" pipeline stage when $match stage should this, since indeed document not altered. right not how happens.
any values may possibly "strings" or @ least not correct bson type need manually cast in order match.
Comments
Post a Comment