I have query with aggregation for MongoDB in my nodejs code.
const query = {
'$expr':{
'$and':[
{'$eq': ['$appId', req.user.appId]},
]
}
}
From the frontend, a filter object is received, as follows:
{
shops: '604c776763c302032e610347',
offset: '0',
limit: '20',
}
I need dynamically push shops id in my query. need to be appId -> user.appID AND targetFrom || targetTo <- shops(from the filter object)
shops can be one id or array of ids, for this I'm using $in operator
query['$expr']['$and'].push({
$eq: [
{
$or: [
{"targetFrom": {$in: bb}},
{"targetTo": {$in: bb}}
]
}
]
})
The old version of code was as follows:
const query = {
$and: [
{appId: req.user.appId}
]
}
query['$and'].push({
$or: [
{"targetFrom": {$in: bb}}, <- in bb is mongodb objectID
{"targetTo": {$in: bb}}
]
})
Update
How I can search some item by ID in my items array of objects?
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]
}
}
]
})
}