Cipriana
Cipriana

Reputation: 393

Partially suppress (project) nested field from MongoDB query

In mongo there is a way to list only the fields that you want in your result, from the documents that match your query conditions. Like this:

db.inventory.find( { status: "A" }, { item: 1, status: 1 } )

as per mongo documentation. This means we will see all all documents where status is A, but we will only see fields "item" and "status" in the result.

However, let's imagine that "item" is a very complex object, out of which I am interested only in a nested field, something like

db.inventory.find( { status: "A" }, { 'item.field1.field2': 1, status: 1 } )

It is true that I get back "item" filtered with only field1.field2, but I would like it to not be nested, so instead of getting back

{
  item: {
    field1: {
      field2
    }
  }
}

but I would like to get only the nested field (field2). Is this possible?

Upvotes: 1

Views: 388

Answers (1)

Christible
Christible

Reputation: 11

db.user_data.aggregate([{$match:{status: "A"},{$group:{"field2":{$first:"$item.field1.field2"}}}}])

Upvotes: 1

Related Questions