10

MongoDb Collection Example (Person):

{
    "id": "12345",
    "schools": [
                {
                    "name": "A",
                    "zipcode": "12345"
                },
                {
                    "name": "B",
                    "zipcode": "67890"
                }
            ]
}

Desired output:

{
    "id": "12345",
    "schools": [
                {
                    "zipcode": "12345"
                },
                {
                    "zipcode": "67890"
                }
            ]
}

My current partial code for retrieving all:

collection.find({}, {id: true, schools: true})

I am querying the entire collection. But I only want to return zipcode part of school element, not other fields (because the actual school object might contain much more data which I do not need). I could retrieve all and remove those un-needed fields (like "name" of school) in code, but that's not what I am looking for. I want to do a MongoDb query.

g.sui
  • 1,550
  • 3
  • 15
  • 20

1 Answers1

14

You can use the dot notation to project specific fields inside documents embedded in an array.

db.collection.find({},{id:true, "schools.zipcode":1}).pretty()
Israel Zinc
  • 2,713
  • 2
  • 18
  • 30
radhakrishnan
  • 1,399
  • 1
  • 14
  • 20