[英]How to do find using node and mongodb?
Below 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 api for find and [{ "name":"John", "rank":1, "year":1998 },{ "name":"Sherif", "rank":1, "year":1999 }]
this is the data i am getting from req.body here i mentioned as a query 我写了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)
});
My expectation this res.json should return only these two documents 我期望这个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"}]
In mongodb we can write like this 在mongodb中,我们可以这样写
db.users.find({rank:1, name:{$in:["John","Sherif"]}, year:{$in:[1998,1999]}})
i want solution in nodejs,express because based on request we need to do find Help me out 我想要在nodejs中解决的方法,表达,因为根据要求我们需要找到帮助我
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"
}
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);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.