jeroen / mongolite

Fast and Simple MongoDB Client for R
https://jeroen.github.io/mongolite/
284 stars 64 forks source link

aggregate-project-unwind-match #191

Closed gulzarahamed closed 4 years ago

gulzarahamed commented 4 years ago

I have following document:-

{ "_id" : ObjectId("54bc46bad4b428b2d2945471"), "customers" : [ { "cust_id" : "A123", "amount" : 500, "status" : "A" }, { "cust_id" : "B123", "amount" : 250, "status" : "B" }, { "cust_id" : "C123", "amount" : 200, "status" : "C" }, { "cust_id" : "D123", "amount" : 300, "status" : "D" } ] }

I queried like this

db.getCollection('orders').find({customers: {$elemMatch: {status: "B"}}})

Expected:-

{ "_id" : ObjectId("54bc46bad4b428b2d2945471"), "customers" : [ { "cust_id" : "B123", "amount" : 250, "status" : "B" } ] }

But it returned entire document and the output was:-

{ "_id" : ObjectId("54bc46bad4b428b2d2945471"), "customers" : [ { "cust_id" : "A123", "amount" : 500, "status" : "A" }, { "cust_id" : "B123", "amount" : 250, "status" : "B" }, { "cust_id" : "C123", "amount" : 200, "status" : "C" }, { "cust_id" : "D123", "amount" : 300, "status" : "D" } ] }

so I tried like this:-

db.getCollection('orders').aggregate( { $project: { "cust_id" : 1, "amount" : 1, "status" : 1 } }, { $unwind: "$customers" }, { $match: { "customers.status": "B" }} )

But it was returned 0 items, I am not sure what i was missed here, can someone help me?

jeroen commented 4 years ago

This question does not seem related to the R package.