Peter
Peter

Reputation: 14098

Retrieve embedded document in MongoDB

I have a collection like with elements like this:

{
    _id: 585b...,
    data: [
        {
            name: "John",
            age: 30
        },
        {
            name: "Jane",
            age: 31
        }
    ]
}

I know how to find the document that contains John:

db.People.find({"data.name", "John"})

But then I get the entire document. How can I get just the embedded document. So I want to return this:

{
    name: "John",
    age: 30
}

For context: this is part of a larger dataset and I need to check if certain updates are made to this specific document. Due to the way the application is implemented, the embedded document won't always be at the same index.

So how can I query and return an embedded document?

Upvotes: 0

Views: 111

Answers (1)

ares
ares

Reputation: 4413

Use a second parameter to suppress the ID

db.people.find({"data.name", "John"}, {_id : 0})

This will output

data: [
    {
        name: "John",
        age: 30
    },
    {
        name: "Jane",
        age: 31
    }
]

To get just the embedded documents, use aggregation.

db.test.aggregate([
  {
    $unwind : "$data"
  },
  {
    $match : {"data.name" : "John"}
  },
  {
    $project : {
      _id : 0,
      name : "$data.name",
      age : "$data.age"
    }
  }
])

Upvotes: 1

Related Questions