user3795202
user3795202

Reputation: 67

MongoDb nested array query excluding on keyword

Below I have listed three zoos. I'm looking for a mongoDB query that will give me all zoos that have an animal with a type other than "dog". For the below documents, the zoos with number 1 and number 3 should be returned because in the animal array there are animals with type not equal to dog.

 {
   "name": "Best zoo ever",
   number: 1,
   "animals": [
     {
       "type": "cat",
       "name": "sylvester"
     },
     {
       "type": "dog",
       "name": "scooby"
     }
   ]
 }

 {
   "name": "nyc zoo",
   number: 2,
   "animals": [
     {
       "type": "dog",
       "name": "scooby"
     }
   ]
 }

 {
   "name": "brooklyn zoo",
   number: 3,
   "animals": [
     {
       "type": "fish",
       "name": "dori"
     }
   ]
 }

Upvotes: 0

Views: 35

Answers (1)

Joe
Joe

Reputation: 82654

You can query with $elemMatch and $ne:

 db.zoos.find({ "animals": { $elemMatch: { type: { $ne: "dog" }} }})

$elemMatch docs

$ne docs

Upvotes: 1

Related Questions