Stepan Poperechnyi
Stepan Poperechnyi

Reputation: 344

Mongo how to exclude nested _id in the nested array

I want to exclude nested default _id in every element of array in the founded result. I have next request. In some fields _id property can be absent. How can I exclude it in the filters ? Is it possible?

db.getCollection('Test').find({"name":"t1"},{"_id":0})

I get next data from DB

       {
            "array" : [ 
                        {
                            "_id": ObjectId("5685ea32ba5298688d27cceb"),
                            "id" : 1,
                            "name" : "aaa"
                        }, 
                        {
                            "_id": ObjectId("5685ea32ba5298688d27cceb"),
                            "id" : 2,
                            "name" : "bbb"
                        },
                        {
                            "id" : 3,
                            "name" : "bbb"
                        },
            ]
}

I want to get next array without _id

       {
            "array" : [ 
                        {
                            "id" : 1,
                            "name" : "aaa"
                        }, 
                        {
                            "id" : 2,
                            "name" : "bbb"
                        },
            ]
}

When I try to use

db.getCollection('Test').find({"name":"t1"},{"_id":0, "array._id":0})

I get the error like:

"errmsg" : "Projection cannot have a mix of inclusion and exclusion.", I think the reason that some objects of array don't contain the _id property

Upvotes: 0

Views: 1431

Answers (1)

turivishal
turivishal

Reputation: 36114

The _id is inside an array field, so you have to use array._id,

db.getCollection('Test').find(
  { "name": "t1" },
  { "array._id": 0 }
)

Playground,
Mongo Shell

Upvotes: 1

Related Questions