How to find using node and mongodb?

Below is the data stored in my collection

[
{ "_id" : ObjectId("53d9feff55d6b4dd1171dd9e"),"name":"John", "rank":1, "year":1998 ,"class":"a" ,"total":"1128" },
{ "_id" : ObjectId("feff553d95d6b4dd19e171dd"),"name":"Sherif", "rank":1, "year":1999 ,"class":"b" ,"total":"1163"},
{ "_id" : ObjectId("9fef53dd6b4dd1171f55dd9e"),"name":"shravan", "rank":1, "year":2000 ,"class":"b" ,"total":"1113"},
{ "_id" : ObjectId("117153d9fef6b4dddd9ef55d"),"name":"aneesh", "rank":1, "year":2001 ,"class":"d" ,"total":"1145"},
{ "_id" : ObjectId("dd9e53feff55d6b4dd1171d9"),"name":"abdul", "rank":1, "year":1997 ,"class":"a" ,"total":"1100"},
]

I wrote an api for find and [{ "name":"John", "rank":1, "year":1998 },{ "name":"Sherif", "rank":1, "year":1999 }], this is the data I get from req.body, which I mentioned as a request

router.post('/users',function(req,res){
  var query =[{ "name":"John", "rank":1, "year":1998 },{ "name":"Sherif", "rank":1, "year":1999 }]
  User.find(query, function(err, result) {
    if (err) throw err;
    console.log(result);
    res.json(result)

  });

My expectation of this res.json is to return only these two documents

[
{ "_id" : ObjectId("53d9feff55d6b4dd1171dd9e"),"name":"John", "rank":1, "year":1998 ,"class":"a" ,"total":"1128" },
{ "_id" : ObjectId("feff553d95d6b4dd19e171dd"),"name":"Sherif", "rank":1, "year":1999 ,"class":"b" ,"total":"1163"}]

In mongodb we can write like this:

db.users.find({rank:1, name:{$in:["John","Sherif"]}, year:{$in:[1998,1999]}})

I want a solution in nodejs, express, because on request we need to find Help me

+1
source share
3 answers

try with mongoose $oroperator

var query = {
  $or : [
    {
      "name":"John", 
      "rank":1,
      "year":1998 
    },
    {
      "name":"Sherif",
      "rank":1, "year":1999 
    }
  ]
}
+5
source

Your search request should look like this:

db.collection.find({rank:1, name:{$in:["John","Sherif"]}, year:{$in:[1998,1999]}})

And the result will be:

/* 1 */
{
"_id" : ObjectId("53d9feff55d6b4dd1171dd9e"),
"name" : "John",
"rank" : 1,
"year" : 1998,
"class" : "a",
"total" : "1128"
}

/* 2 */
{
"_id" : ObjectId("feff553d95d6b4dd19e171dd"),
"name" : "Sherif",
"rank" : 1,
"year" : 1999,
"class" : "b",
"total" : "1163"
}
+1
source

, , :

router.post('/users',function(req, res, next) {
    // req.body = [{ "name":"John", "rank":1, "year":1998 },{ "name":"Sherif", "rank":1, "year":1999 }]

    // mapping users to each array
    const query = { $or: req.body };
    // execute query
    User.find(query, function(err, result) {
        if (err) next(err);
        console.log(result);
        res.json(result);
    });
});
0
source

Source: https://habr.com/ru/post/1614594/


All Articles