简体   繁体   中英

How can I make a multiple options query with mongodb driver for nodejs?

I'm working in a MongoDB query with Nodejs and I have a problem that I can't resolve.

Let us supposed we have a lot of documents in Mongo and each document have a tags array

tags: [tag1, tag2, tag3]

Front-end are going to send the parameters and we want to make a query with those... How can I find every document inside Mongo with those tags. The tags can be differents, not all documents have the same tags but I want to pull each document that have almost one of those tags. I don't know if I make myself clear with this but I hope you'll help me.

PD: If the query works, we have more than 13 that I can apply so it needs to be something like dynamically query o something.

Regards

This is where the mongodb's aggregate function comes in play

lets say there is a database called books and we want to get books that contain lets say ['fantasy', 'sci-fi'] in its genres

db.book.aggregate([{
   $match:{
     genres:{
      $in:['fantasy', 'sci-fi']
      }
   }
}])

this will get the result you want, finding all the books that contain either fantasy, or scifi

db.book.aggregate([{
   $match:{
     genres:{
      $all:['fantasy', 'sci-fi']
      }
   }
}])

This will get all the books that have genres with both fantasy and sf

db.book.aggregate([{
   $match:{
     genres:{
      $nin:['fantasy', 'sci-fi']
      }
   }
}])

This will fetch all the books that don't have these values

generate an $or condition in your code according to the parameters:

let or_array = [];
params.forEach(params, (tag_param) => {
       or_array.push({tags: tag_param})
     });
let or_cond = {$or: or_array};

now we just need a simple find query to retrieve the documents:

  let results = model.find(or_cond); 

results should contain the wanted documents.

** note that $or requires a none empty array so you should validate at least one parameter is received from the client side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM