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 [email protected], id is domainOwner and scope is clearcrimson?

Document:

{ 
    "_id" : "7Rc5q2o3Qnv7j2HuT", 
    "emails" : [
        {"address" : "[email protected]"},
        {"address" : "[email protected]"},
    ], 
    "roles" : [
        {"_id" : "domainOwner", "scope" : "clearcrimson"}, 
        {"_id" : "domainOwner", "scope" : "clearcrimson2"}
    ]
}
1
  • 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. Commented Nov 11, 2019 at 6:26

1 Answer 1

1
db.getCollection("users").findOne({ "roles": {$elemMatch: { "_id": "domainOwner", "scope": "clearcrimson"}}, "emails.address": "[email protected]" })

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": "[email protected]" }, {_id: 1, "roles.$": 1, emails: 1})

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.