Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to projection element in array field of MongoDb collection?

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.

like image 909
g.sui Avatar asked Mar 21 '17 04:03

g.sui


1 Answers

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()
like image 54
radhakrishnan Avatar answered Nov 01 '22 17:11

radhakrishnan