1

I'm working on a project where I'm trying to return a document, but exclude some child fields based on status. For example if the status is disabled then I don't want that child returned. But all the other records returned if they don't contain disabled.

How do I select the document, but exclude records from the child array based on a value.

Thanks

My document look like this:

{
    "_id" : ObjectId("5e7bb266071f9601b6ad8f4e"),
    "name" : "Test Document",
    "postcode" : "90210",
    "colors" : [ 
        {
            "_id" : ObjectId("5e7d276a05674f0cf49bdcec"),
            "color" : "blue",
            "status": "active"

        }, 
        {
            "_id" : ObjectId("5e7d276a05674f0cf49bdceg"),
            "color" : "red",
            "status": "active"
        }, 
        {
            "_id" : ObjectId("5e7d276a05674f0cf49bdceh"),
            "color" : "green",
            "status" : "disabled"
        }
    ]
}

How do I return:

{
    "_id" : ObjectId("5e7bb266071f9601b6ad8f4e"),
    "name" : "Test Document",
    "postcode" : "90210",
    "colors" : [ 
        {
            "_id" : ObjectId("5e7d276a05674f0cf49bdcec"),
            "color" : "blue",
            "status": "active"

        }, 
        {
            "_id" : ObjectId("5e7d276a05674f0cf49bdceg"),
            "color" : "red",
            "status": "active"
        }
    ]
}

I have been trying variations of:

    $and: [{
            _id: mongodb.ObjectId("5e7bb266071f9601b6ad8f4e")
        }, {
            "colors.$.status": "active"
           }]
tbowden
  • 1,008
  • 1
  • 19
  • 44
  • `find` and friends can only return the entire document, or include exclude fields by name. I doesn't have a way to exclude array elements based on content. You could do that with aggregation and [$filter](https://docs.mongodb.com/manual/reference/operator/aggregation/filter/index.html) – Joe Mar 29 '20 at 00:39

0 Answers0