簡體   English   中英

MongoDB:如何為多個可選值設置條件

[英]MongoDB : how to put conditional for multiple optional value

如何在mongoDB中應用多條件查找具有相同鍵名的條件?

我在MongoDB中有集合:

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

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

提前致謝 :)

您需要使用$or運算符創建查詢對象,如下所示:

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

然后使用它作為查詢

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM