Stezy
Stezy

Reputation: 390

MongoDB aggregation filter array of subdocuments by missing field

Given the following collection:

db.test.insertOne(
    {
        test: [
            {a: "1", b: "2"},
            {a: "3"}
        ]
    }
)

How can you filter out the second document (with the non existing field b) of the test array inside an aggregation?

The aggregation

db.test.aggregate([
    {
        $project: {
            test: {
                $filter: {
                    input: "$test",
                    cond: {
                        $ne: ["$$this.b", null]
                    }
                }
            }
        }
    }
])

still returns the subdocument with the not existing field b:

{
    "_id": {"$oid": "xyz"},
    "test": [
      {
        "a": "1",
        "b": "2"
      },
      {
        "a": "3"
      }
    ]
  }

I'd expect the following result:

{
    "_id": {"$oid": "xyz"},
    "test": [
      {
        "a": "1",
        "b": "2"
      }
    ]
  }

Obviously my pipeline is more complex than that, but the problem boils down to this small example.

Upvotes: 0

Views: 1034

Answers (1)

Joe
Joe

Reputation: 28316

Null and missing are different types in BSON. To test for missing, compare with the $type:

                    cond: {
                        $ne: [{$type:"$$this.b"}, "missing"]
                    }

Playground

Upvotes: 4

Related Questions