0

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?

Peter
  • 13,733
  • 11
  • 75
  • 122
  • 1
    Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – styvane Dec 22 '16 at 12:44

1 Answers1

1

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"
    }
  }
])
ares
  • 4,283
  • 6
  • 32
  • 63