6

I have the collection BookingDetails with below record:

    {
      "code" : "TICKET1234",
        "orderDetails" : [
          {
            "cost": 150.0,
            "movieName": "avengers"
          }
        ]
    },
    {
      "code" : "TICKET1235",
        "orderDetails" : [

        ]
    }

Need to check if the orderDetails.MovieName exists or not on the projection layer. I tried below query, it is not helpful.

    db.BookingDetails.aggregate([
      {
        $project: {
          OrderExists: {
            $cond: [
              { $ne: ["$orderDetails.0.movieName", null] },
              1, 0
            ]
          }
        }
      }
    ])

I can't use $exists inside $cond. I tried $ifNull as well. Need your thoughts on this.

4 Answers 4

9

Another approach in the the mongoshell is :

db.getCollection('nestedstuff').find({
 'mainObj.level1.level2.level3.seekObj': { 
    $elemMatch: {
      'propertyToFind': {
         $exists: true
        }
     }
   }
}).count()
Sign up to request clarification or add additional context in comments.

Comments

3

You can use below aggregation

db.collection.aggregate([
  { "$project": {
    "OrderExists": {
      "$cond": [{ "$ne": [{ "$ifNull": [{ "$arrayElemAt": ["$orderDetails.movieName", 0] }, null] }, null] }, 1, 0]
    }
  }}
])

Comments

1

Have you tried using Type Check to find null values ​​with {$ type: 10}?
Directly from the documentation:

Type Check

The { item : { $type: 10 } } query matches only documents that contain the item field whose value is null; i.e. the value of the item field is of BSON Type Null (type number 10) :

Comments

1

The following query can get us the expected output:

db.collection.aggregate([
  {
    $project:{
      "OrderExists":{
        $cond:[
          {
            $ne:[
              { 
                $arrayElemAt: ["$orderDetails.movieName", 0] 
              },
              undefined
            ]
          },
          1,
          0
        ]
      }
    }
  }
]).pretty()

Data set:

{
  "_id" : ObjectId("5d837db4fb35a835fbd8638f"),
  "code" : "TICKET1234",
  "orderDetails" : [
    {
      "cost" : 150,
      "movieName" : "avengers"
    }
  ]
}
{
  "_id" : ObjectId("5d837db4fb35a835fbd86390"),
  "code" : "TICKET1235",
  "orderDetails" : [ ]
}

Output:

{
  "_id" : ObjectId("5d837db4fb35a835fbd8638f"),
  "OrderExists" : 1
}
{
  "_id" : ObjectId("5d837db4fb35a835fbd86390"),
  "OrderExists" : 0
}

Comments

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.