How to do find using node and mongodb?

前端 未结 3 1205
清歌不尽
清歌不尽 2020-12-07 05:06

Below Data stored in my collection

[
{ \"_id\" : ObjectId(\"53d9feff55d6b4dd1171dd9e\"),\"name\":\"John\", \"rank\":1, \"year\":1998 ,\"class\":\"a\" ,\"tota         


        
相关标签:
3条回答
  • 2020-12-07 05:36

    Although a few people have answered, but I believe complete way to do it is:

    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 讨论(0)
  • 2020-12-07 05:39

    Your find query should will look like this:

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

    And the result would 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"
    }
    
    0 讨论(0)
  • 2020-12-07 05:53

    try with mongoose $or operator

    var query = {
      $or : [
        {
          "name":"John", 
          "rank":1,
          "year":1998 
        },
        {
          "name":"Sherif",
          "rank":1, "year":1999 
        }
      ]
    }
    
    0 讨论(0)
提交回复
热议问题