sankar
sankar

Reputation: 278

mongo "$and" operator for subcollection

  {
   "movies":[
      {
         "moviename":"Avengers",
         "characters":[
            "Hulk",
            "Iron man"
         ]
      },
      {
         "moviename":"Justice League",
         "characters":[
            "Super man",
            "Wonder Woman"
         ]
      }
   ]
}

I want to fetch Document based on the query of Moviename and Characters both should match like Moviename ="Avengers" and charactername="Hulk" then it should return value. if i pass Moviename="Avengers" and charactername="Super man" then it shouldn't return anything I have written a query which is basically works like or instead of and {"$and" : [{"movies.moviename" : { "$in" : ["Avenger"] },"movies.characters" :{"$in":["Super man"]}}]} This query shouldn't return anything but it return both the documents. It matches my moviename and characters separately not on the same object.

Upvotes: 2

Views: 108

Answers (2)

sankar
sankar

Reputation: 278

{ "movies" : { "$elemMatch" : {"moviename" :"Avengers" , "characters":{"$in":["Hulk"]}}}}

Ok after little reading found the solution .$elemMatch solve this problem. more reading here https://docs.mongodb.com/manual/reference/operator/query/elemMatch/#op._S_elemMatch

Upvotes: 1

tutiplain
tutiplain

Reputation: 1480

There might be a simpler way to do this, but you might want to try $where. This accepts a JS function where you have access to the document structure, and can manually iterate through the arrays within the document and return true for those which satisfy your critera. Note, though, these type of queries can be slow if your collection is big. Here's a link to its documentation: https://docs.mongodb.com/manual/reference/operator/query/where/

Upvotes: 1

Related Questions