Javascript 猫鼬“查找”具有多种条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33627238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:17:16  来源:igfitidea点击:

mongoose "Find" with multiple conditions

javascriptnode.jsmongodbmongoose

提问by Skywalker

I am trying to get data from my mongoDB database by using mongoose filters. The scenario is that each user object in the database has certain fields like "Region"or "Sector".

我正在尝试使用 mongoose 过滤器从我的 mongoDB 数据库中获取数据。场景是数据库中的每个用户对象都有某些字段,例如"Region""Sector"

Currently I am getting all the users that contain the keyword "region"in there object like so:

目前,我正在获取所有在对象中包含关键字“区域”的用户,如下所示:

 // Filter all healthcare bios by region
 app.get('/user',function(req, res) {

 // use mongoose to get all users in the database
 User.find({region: "NA"}, function(err, user) 
 {
    // if there is an error retrieving, send the error. nothing after res.send(err) will execute
    if (err)
    {
        res.send(err);
    }
    // return all todos in JSON format
    console.log(user);
    res.json(user);

});
});

How can put some conditions in mongoose that it return users that contain both "region" && "Sector" in their objects.Currently its only returning the user which have the region keyword in them.

如何在 mongoose 中放置一些条件,使其返回在其对象中同时包含“区域”和“扇区”的用户。目前它只返回包含 region 关键字的用户。

I have tried using $and operator but I couldn't get it to work.

我曾尝试使用 $and 运算符,但无法使其正常工作。

回答by Vishnu

app.get('/user',function(req, res) {

 User.find({region: "NA",sector:"Some Sector"}, function(err, user) 
 {
    if (err)
    {
        res.send(err);
    }
    console.log(user);
    res.json(user);

 });
});

If you want data with either region:"NA" or sector:"Some Sector". you can use $oroperator.

如果您想要带有区域:“NA”或扇区:“某些扇区”的数据。您可以使用$or运算符。

User.find({$or:[{region: "NA"},{sector:"Some Sector"}]}, function(err, user) 
 {
    if (err)
    {
        res.send(err);
    }
    console.log(user);
    res.json(user);

 });

回答by Ron Wertlen

If you want results that contain any region or sector as long as both are present at the same time you need the following query in your User.find: {region: {$exists:true},sector: {$exists:true}}

如果您想要包含任何区域或部门的结果,只要两者同时存在,您需要在您的User.find: {region: {$exists:true},sector: {$exists:true}}

,is the equivalent of $andas long as you are searching different fields.

,就相当于$and您在搜索不同的字段。