MongoDB:如何为多个可选值放置条件

时间:2022-02-05 02:33:21

How to apply multi condition in mongoDB find condition with same key name??

如何在mongoDB中应用多条件查找具有相同键名的条件?

I have collection in MongoDB:

我在MongoDB中有收藏:

[{
    'name': 'test1',
    'brand': 'A'
}, {
    'name': 'test2',
    'brand': 'B'
}, {
    'name': 'test3',
    'brand': 'C'
}, {
    'name': 'test4',
    'brand': 'D'
}]

server.js

server.js

app.get('/products', function(request, response) {
    // request.query => {'brand': 'A', 'brand: 'B', 'brand': 'C'}
    mongoose.model('products').find(request.query, function(err, data) {
        response.json(data);
        // data shoule be matching only if 'brand': 'A' or 'brand': 'B' or brand: 'C'
    });
});

Thanks in advance :)

提前致谢 :)

1 个解决方案

#1


3  

You'll need to create the query object using $or operator, like this:

您需要使用$或运算符创建查询对象,如下所示:

var query = { $or: [] };
for (key in req.query)
    query.$or.push({ key: request.query[key] });
//=> { $or: [ {brand: 'A'}, {brand: 'B'},  …] }

Then use that as your query

然后使用它作为您的查询

Model.find(query, function(err, data){
    res.json(data);
});

#1


3  

You'll need to create the query object using $or operator, like this:

您需要使用$或运算符创建查询对象,如下所示:

var query = { $or: [] };
for (key in req.query)
    query.$or.push({ key: request.query[key] });
//=> { $or: [ {brand: 'A'}, {brand: 'B'},  …] }

Then use that as your query

然后使用它作为您的查询

Model.find(query, function(err, data){
    res.json(data);
});