简体   繁体   中英

How to $match multiple values for MongoDB Mongoose query

I am trying to find specific fields for more than one value. For example, I have a database with different countries and I am trying to retrieve their name, year, and nominalGDP (renamed to y in the result for some other important reason). It works perfect for this example, where I am only retrieving from USA, but how would I add another country like China or whatever?

Country.aggregate([
  {
    $match: {
      name: "USA"
    }
  },
  {
    $project: {
      _id: 0,
      name: 1,
      year: 1,
      'y' : '$nominalGDP'
    }
  }
], function(err, recs){
  if(err){
    console.log(err);
  } else {
    console.log(recs);
  }
});

This is probably really simple but I have not been able to find out how.

Use $in operator to specify more than one matching option. For example:

{
   $match: {
      name: { $in: [ "USA", "China" ] }
   }
}
`const results = await SchemaName.find([{$match:{name:{$in:["USA","China"]}}}])
res.status(200).json(results);`

but if you are getting the country names from frontend through the body or something then:

` const allCountries = req.body.allCountries;
  var result;
  for(let i=0; i < allCountries.length; i++){
   result = await SchemaName.find([{$match:{name:{$in:allCountries[i]}}}]) 
   }
`

assuming you are building asynchronous functions...

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