Ijaz
Ijaz

Reputation: 461

Mongo query to find not null string inside list of objects

I want to query an array of objects with a particular key should have text in it.

this is the query I have tried

to find disclaimer.text exists and not empty. But It always prints 0

 db.slideshows.count({"config.slides": { $elemMatch: {disclaimer: {"text" :   {"$exists" : true, "$ne" : ""}  }} } })

This is my data

 {
 "id": 1002,
 "config": {
"firstSlide": "vehicle",
"slides": [
  {
    "slideKey": "sk1",
    "disclaimer": {
      "text": ""
    }
  },
  {
    "slideKey": "sk2"
   }
  ]
 }
}

{
"id": 1003,
"config": {
"firstSlide": "book",
"slides": [
  {
    "slideKey": "sk3",
    "disclaimer": {
      "text": "Hello"
    }
  },
  {
    "slideKey": "sk4"
   }
  ]
 }
}

{
"id": 1004,
"config": {
"firstSlide": "book",
"slides": [
  {
    "slideKey": "sk3",
    "disclaimer": {
      "text": "nope"
    }
  },
  {
    "slideKey": "sk4",
    "disclaimer": {
      "text": ""
    }
   }
  ]
  }
 }

I want all the rows which have not empty disclaimer.text. ex. in the above set I need to get id 1004 and 1003 as a result.

Upvotes: 0

Views: 100

Answers (1)

sushant mehta
sushant mehta

Reputation: 1274

Try

db.slideshows.count({
  "config.slides": {
    $elemMatch: {
      "disclaimer.text": {
        "$exists": true,
        "$ne": ""
      }
    }
  }
})

Upvotes: 1

Related Questions