How to create 'not-in' and 'in' query in mongodb?

beginer
beginer
1544 Points
52 Posts

Suppose we have following inventory collection:

db.inventory.insertMany( [
   { "item": "Pens", "quantity": 390, "tags": [ "school", "office" ] },
   { "item": "Erasers", "quantity": 115, "tags": [ "school", "home" ] },
   { "item": "Maps", "tags": [ "office", "storage" ] },
   { "item": "Books", "quantity": 5, "tags": [ "school", "storage", "home" ] }
] )

Want write two query to fetch documents that are:

  1. quantity not in 5 and 115
  2. tags in home

 

Views: 400
Total Answered: 1
Total Marked As Answer: 0
Posted On: 21-Dec-2022 22:04

Share:   fb twitter linkedin
https://www.mongodb.com/docs/manual/reference/operator/query/nin/
 - Smith  01-Jan-2023 03:03
Answers
Jak
Jak
908 Points
132 Posts
         

#1

db.inventory.find( { quantity: { $nin: [ 5, 115 ] } })

Output

{ "item": "Erasers", "quantity": 115, "tags": [ "school", "home" ] },
{ "item": "Books", "quantity": 5, "tags": [ "school", "storage", "home" ] }

#2

db.inventory.find( { tags: { $in: ["home"] } })

Output

{ "item": "Erasers", "quantity": 115, "tags": [ "school", "home" ] },
{ "item": "Books", "quantity": 5, "tags": [ "school", "storage", "home" ] }
Posted On: 03-Jan-2023 00:09
 Log In to Chat