Francisco Barros
Francisco Barros

Reputation: 319

Select documents in which all objects of an array have some value

Good evening I am having trouble navigating MongoDB docs and understanding how to perform, what otherwise looks like, a simple query.

Let us imagine I have the following document:

{
   "user_name": "john doe"
   "friendsList": [
      {"name": "maria"}, 
      {"name": "maria"},
      {"name": "maria"}
   ]
}

I would like to retrieve a document by "user_name": "john doe" (it's unique), but only if all objects inside friendsList array have name = maria. In other words, the Document above would be returned, but the one represented below would result in no matches.

{
   "user_name": "john doe"
   "friendsList": [
      {"name": "maria"}, 
      {"name": "stryx"},
      {"name": "maria"}
   ]
}

I have tried using $all query selectors among others, but all of them resulted in a behaviour where at least one object in the array matches.

Upvotes: 1

Views: 191

Answers (1)

turivishal
turivishal

Reputation: 36104

Try $elemMatch with $not operator,

  • $elemMatch with name is not equal to maria and negative check using $not of elemMatch result it means all the elements should contain maria name
  • $ne to ignore empty friendList, this is optional
db.collection.find({
  user_name: "john doe",
  "friendsList": {
    $ne: [],
    $not: {
      $elemMatch: {
        name: { $ne: "maria" }
      }
    }
  }
})

Playground

Upvotes: 1

Related Questions