3

I have an array of objects and in the $project pipeline of MongoDB I have to choose the one element whose metadata does not exist. So, for example below are a few documents after my $group pipeline -

{
  _id: {
      genre: "suspense",
    },
   price: 10210.6,
   data: [
      {
        subGenre: "Thriller",
        flag: true,
      },
      {
        subGenre: "jumpScare",
      },
      {
        subGenre: "horror",
        flag: true,
      }
    ]
}

After this, I need to run a $project pipeline where I have to only project that element of the data array where the flag does not exist. My syntax for that is -

db.collection.aggregate([
  {
    "$project": {
      "_id": 0,
      "price": 1,
      "data": {
        "$getField": {
          "field": "subGenre",
          "input": {
            "$first": {
             "$filter": { input: "$data", cond: { "$exists": [ "$$this.flag", false ] } }
            }
          }
        }
      }
    }
  }
])

But this is throwing an error -

Invalid $project :: caused by :: Unrecognized expression '$exists'

The output should be -

{
  price: 10210.6,
  subGenre: "jumpScare"
}

1 Answer 1

2

Instead of using $exists which is invalid, you can compare the value with:

$eq: [
  "$$this.flag",
  undefined
]

This aims to check whether the flag field does not exist.

Demo @ Mongo Playground


You may also work with checking the $type value is matched with "missing". (Tested this works in MongoDB Compass)

$eq: [
  { $type: "$$this.flag" },
  "missing"
] 
Sign up to request clarification or add additional context in comments.

3 Comments

This works fine here in thre mongo playground but its not returning any value in my mongodb compass and in my code also in nodejs idk why
Also why is $exists invalid? Is there any other way instead of these both?
Updated the answer. $exists is a query operator, not possible to work in the aggregation pipeline.

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.