我在我的nodejs代码中使用MongoDB聚合查询遇到了问题。
const query = {
'$expr':{
'$and':[
{'$eq': ['$appId', req.user.appId]},
]
}
}
从前端接收到一个筛选对象,如下所示:
{
shops: '604c776763c302032e610347',
offset: '0',
limit: '20',
}
我需要在查询中动态推送商店ID。需要是 appId -> user.appID AND targetFrom || targetTo <- 商店(来自过滤器对象的)
商店可以是一个ID或一组ID,为此我使用了$in
运算符。
query['$expr']['$and'].push({
$eq: [
{
$or: [
{"targetFrom": {$in: bb}},
{"targetTo": {$in: bb}}
]
}
]
})
旧版本的代码如下:
const query = {
$and: [
{appId: req.user.appId}
]
}
query['$and'].push({
$or: [
{"targetFrom": {$in: bb}}, <- in bb is mongodb objectID
{"targetTo": {$in: bb}}
]
})
更新
如何在我的对象数组items
中通过ID搜索某个item
?
if(req.query.products) {
typeof req.query.products === 'string' ? req.query.products = [req.query.products] : req.query.products
let bb = req.query.products.map(function(el) { return mongoose.Types.ObjectId(el) })
query['$expr']['$and'].push({
$and: [
{
items: {
$in: ['item.itemId', bb]
}
}
]
})
}
ISOdateString
?它可以是一个Date
对象(在 MongoDB 中提供了一个别名叫做ISODate
),或者是一个String
- 没有其他的。 - Wernfried Domscheitarray1.push(...array2)
代替array1=array1.concat(array2)
。此外,如果你正在从req.query
或req.body
动态构建查询,请参考这个链接。 @Bob,我会研究一下的。 - Anuj Pancholi