0

I am trying to query a mongodb document without luck. The following query works to get a user whose id is domainOwner and scope is clearcrimson.

db.getCollection("users").findOne( { "roles": { $elemMatch: {_id: "domainOwner", scope: "clearcrimson" } } }, {_id:1})

How can I modify the query to get a user whose one email id could be a@b.com, id is domainOwner and scope is clearcrimson?

Document:

{ 
    "_id" : "7Rc5q2o3Qnv7j2HuT", 
    "emails" : [
        {"address" : "a@b.com"},
        {"address" : "c@d.com"},
    ], 
    "roles" : [
        {"_id" : "domainOwner", "scope" : "clearcrimson"}, 
        {"_id" : "domainOwner", "scope" : "clearcrimson2"}
    ]
}
Ajit Goel
  • 4,180
  • 7
  • 59
  • 107
  • There is nothing new in the question which I can see. Overall you just want to the document which is having double conditions matched inside the array. The only difference is the **document fields** nothing more than that. – Ashh Nov 11 '19 at 06:26

1 Answers1

1
db.getCollection("users").findOne({ "roles": {$elemMatch: { "_id": "domainOwner", "scope": "clearcrimson"}}, "emails.address": "a@b.com" })

As you are using $elemMatch to match multiple conditions in a single object of the array, you can use simple arrayName.fieldName to match for a single condition, like I did with "emails.address" in query above.

You can use $ (positional operator to project only matched object from array)

db.getCollection("users").findOne({ "roles": {$elemMatch: { "_id": "domainOwner", "scope": "clearcrimson"}}, "emails.address": "a@b.com" }, {_id: 1, "roles.$": 1, emails: 1})

We can not use two positional operators in one projection stage. I am using mongo version 3.4.

niranjan_harpale
  • 2,048
  • 1
  • 17
  • 21