Nandy
Nandy

Reputation: 696

MongoDB - Check if the key exists on the array of object

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.

Upvotes: 6

Views: 9426

Answers (4)

Numant Santz
Numant Santz

Reputation: 180

Another approach in the the mongoshell is :

db.getCollection('nestedstuff').find({
 'mainObj.level1.level2.level3.seekObj': { 
    $elemMatch: {
      'propertyToFind': {
         $exists: true
        }
     }
   }
}).count()

Upvotes: 9

Himanshu Sharma
Himanshu Sharma

Reputation: 3010

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
}

Upvotes: 1

Massifox
Massifox

Reputation: 4487

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) :

Upvotes: 1

Ashh
Ashh

Reputation: 46461

You can use below aggregation

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

Upvotes: 3

Related Questions