0

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.

1 Answer 1

4

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

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

Playground

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this, this solves the problem. But how is this working then: docs.mongodb.com/manual/tutorial/query-for-null-fields Shouldn't this logic apply everywhere?
A special case was added to the query language so that null would match nonexistent, but that appears to be the only place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.