Tony Chou
Tony Chou

Reputation: 604

Omit certain field in an array mongo query

Similar to Query for a field in an object in array with Mongo? The asker want to query a specific field in an object, but what I want is opposite to him.

My data

{   "_id": "ffb76dea811a6773c9481fd35262fe7f", 
    "fieldA" : "A", 
    "fieldB" : "B", 
    "fieldC" : [ 
        { "group1" : "100", "group2" : "200", "id" : "b0a05edd3cb0d35674174f34da1b3021"}, 
        { "group1" : "110", "group2" : "230", "id" : "b9071b34c21f948e69cb39df7dbf10a7"} 
    ]
}

How to query to get

{
    "fieldA" : "A", 
    "fieldC" : [ 
        { "group1" : "100", "group2" : "200" }, 
        { "group1" : "110", "group2" : "230" } 
    ]
}

Key point is that I don't want id appear in my query result

db.test.insertOne({"_id":"ffb76dea811a6773c9481fd35262fe7f","fieldA":"A","fieldB":"B","fieldC":[{"group1":"100","group2":"200","id":"b0a05edd3cb0d35674174f34da1b3021"},{"group1":"110","group2":"230","id":"b9071b34c21f948e69cb39df7dbf10a7"}]})

Upvotes: 1

Views: 3857

Answers (1)

Ayush Gupta
Ayush Gupta

Reputation: 9295

The second parameter of a find in mongoDB is a projection option which is used to include or exclude fields from the result. In your case, you need to use it as follows:

db.test.find({},{"fieldC.id":0, fieldB: 0, "_id":0})

See here for how projection works https://docs.mongodb.com/manual/reference/method/db.collection.find/

Upvotes: 6

Related Questions