Jeff
Jeff

Reputation: 149

How can I return only one field in a mongo array of objects without removing rest of object

I am querying a collection and in that collection I have an array of objects. In that array I want to use projection to only return one field in every object. However, I do not want to remove all the data outside that object.

Let's say one document in the collection looks like this

{
  "a": "some val",
  "b": "some other val",
  "c": [
    {
      "d": "some array val",
      "e": "some other array val"
    }
  ]
}

And let's say I want to remove every field in the array besides 'd' and end up with

{
  "a": "some val",
  "b": "some other val",
  "c": [
    {
      "d": "some array val",
    }
  ]
}

I tried:

db.collection.find({}, { "c.d": 1 })

but this removed "a" and "b" as well and just returned:

{
  "c": [
    {
      "d": "some array val",
    }
  ]
}

Also, I cannot do:

db.collection.find({}, { "c.e": 0 })

because there may be other fields besides 'e' and those should be hidden as well.

Upvotes: 2

Views: 829

Answers (1)

mickl
mickl

Reputation: 49985

You can run $addFields to overwrite existing field and $map to transform c array and take only d values, try:

db.collection.aggregate([
    {
        $addFields: {
            c: {
                $map: {
                    input: "$c",
                    in: { d: "$$this.d" }
                }
            }
        }
    }
])

Upvotes: 2

Related Questions