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

beginer
beginer
314 Points
87 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: 104
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
Member
406 Points
168 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