Home > OS >  filter out related products from mongodb collection
filter out related products from mongodb collection

Time:10-26

Product document:

title: 'product title',
price: 240,
tags: [ 'snacks', 'vegetable' ],

User search query: /search?tags=snacks,fruit,juice. Here, user selected multiple tags (snacks, fruit and juice). I want to select all documents that contain at least one of the tags user searched for using mongodb aggregation pipeline.

CodePudding user response:

You can use the $in operator to find documents where a field contains any item in a given array.

{
  tags: { 
    $in: ['snacks', 'fruit', 'juice' ]
  }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

$in

db.collection.find({
  "tags": {
    "$in": [
      "snacks",
      "fruit",
      "juice"
    ]
  }
})

mongoplayground

  • Related