如何使用node和mongodb查找?

时间:2018-04-06 04:51:31

标签: node.js express

以下数据存储在我的收藏中

[
{ "_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"},
]

我写了api for find和[{ "name":"John", "rank":1, "year":1998 },{ "name":"Sherif", "rank":1, "year":1999 }]这是我从req.body得到的数据,我在这里作为查询提到

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)

  });

我的期望这个res.json应该只返回这两个文件

[
{ "_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"}]

在mongodb中,我们可以这样写

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

我想在nodejs中使用解决方案,因为根据请求我们需要进行查找 帮帮我

3 个答案:

答案 0 :(得分:5)

尝试使用mongoose $or运算符

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

答案 1 :(得分:1)

您的查找查询应如下所示:

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

结果将是:

/* 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"
}

答案 2 :(得分:0)

虽然有几个人已经回答,但我相信完整的方法是:

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);
    });
});