Josh Thomas
Josh Thomas

Reputation: 1677

How to fetch document with filtered nested document using Mongo query?

Here is my organization collection.

[{
    "_id" : ObjectId("5fd5fc1b9f117029b5233b2e"),
    "name" : "ClassA",
    "orgMembers" : [ 
        {
            "_id" : ObjectId("5fd5fc1b9f117029b5233b2f"),
            "userId" : "Ben",
        },
        {
            "_id" : ObjectId("5fd5fc1b9f117029b5233b2f"),
            "userId" : "Anton",
        }
    ],
},
{
    "_id" : ObjectId("5fd5fc1b9f117029b5233b2e"),
    "name" : "ClassA",
    "orgMembers" : [ 
        {
            "_id" : ObjectId("5fd5fc1b9f117029b5233b2f"),
            "userId" : "Ben",
        }
    ],
}]

Each document has properties like _id, name, orgMembers which represent document information. And orgMembers is the Array of Members (_id, userId) who belongs to organization.

In this collection, I want to fetch the organizations which includes orgMember with Anton as userId and as well orgMembers of fetched organization document should only contain Anton as a orgMember.

Expected Result is likewise

[{
    "_id" : ObjectId("5fd5fc1b9f117029b5233b2e"),
    "name" : "ClassA",
    "orgMembers" : [
        {
            "_id" : ObjectId("5fd5fc1b9f117029b5233b2f"),
            "userId" : "Anton",
        }
    ],
}]

Here ClassA organization has two orgMembers but need to be filtered matching with userId.

I have tried with

documentModel.find({ 'orgMembers.userId': 'Anton' })

But within this query, I get the result like this.

[{
    "_id" : ObjectId("5fd5fc1b9f117029b5233b2e"),
    "name" : "ClassA",
    "orgMembers" : [ 
        // should be omitted 
        {
            "_id" : ObjectId("5fd5fc1b9f117029b5233b2f"),
            "userId" : "Ben",
        },

        // should be contained
        {
            "_id" : ObjectId("5fd5fc1b9f117029b5233b2f"),
            "userId" : "Anton",
        }
    ],
}]

For expected result, orgMember with userId: Ben should be omitted.

How can I get my expected result with mongo query?

Upvotes: 0

Views: 44

Answers (2)

abhilash reddy
abhilash reddy

Reputation: 1

not sure if i quite got your requirement:

but try this if it works

db.collection.find({
  "orgMembers.userId": {
    $regex: "Anton",
    $options: "i"
  }
},
{
  name: 1,
  "orgMembers.$": 1
})

this is to return only the userId you are looking for in orgMembers.if there are more orgmembers they will not be part of output

Upvotes: 0

Kevin Li
Kevin Li

Reputation: 150

I believe this will be worked on your side

db.collection.find({
  "orgMembers.userId": "Anton"
},
{
  orgMembers: {
    "$elemMatch": {
      userId: "Anton"
    }
  }
})

Upvotes: 1

Related Questions