[英]How to get the connected objects within a collection in an array in Mongoose MongoDb NodeJS
[英]MongoDB aggregation search in objects of array [nodejs, mongoose]
我从客户端得到一个过滤器 object ,例如:
{
appId: "01",
items: [ '60522e84feecf7036fa11831', '60522c47feecf7036fa1182d' ],
//offset limit
}
我的查询是:
await someCollection.aggregate([
{ $match: query },
{
$group: {//some fields}
},
])
.sort({date: -1})
.skip(+req.query.offset)
.limit(+req.query.limit)
集合是:
[
{
"_id": 1,
"shop": 1,
"appId": "01",
"items": [
{
"itemId": "777"
},
{
"itemId": "666"
},
]
},
{
"_id": 2,
"shop": 2,
"appId": "01",
"items": [
{
"itemId": "666"
},
{
"itemId": "123"
},
]
},
{
"_id": 3,
"shop": 2,
"appId": "01",
"items": [
{
"itemId": "x"
},
]
}
]
在我的后端查询上动态生成:
const query = {
'$expr':{
'$and':[
{'$eq': ['$appId', req.user.appId.toString()]},
]
}
}
如果即将到来的查询有一个 products 数组,我需要在 objects 数组中搜索 id 。 例如: ['777', 'x'] 结果需要有 2 个项目,其中"_id": 1 和 "_id": 3
我的代码是:
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({
$or: [{
$eq: ['$items.itemId', bb]
}],
}
}
所以,我需要使用$in运算符与$match & $and动态地,但我不知道如何
我会这样尝试:
const query = { ['$or']: [] }
for (let k of Object.keys(req.user)) {
if (Array.isArray(req.user[k])) {
for (let i in req.user[k])
query['$or'].push({ [`${k}.itemId`]: mongoose.Types.ObjectId(i) });
} else {
query[k] = req.user[k].toString();
}
}
await someCollection.aggregate([
{ $match: query },
{
$group: {//some fields}
},
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.