我在我的 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}}
]
})
uj5u.com熱心網友回復:
請查看以下是否滿足您的要求:
Mongoplayground 鏈接
假設:
req.user.appId是一個字串。bb是 objectIds 或字串 ([ObjectId("asdfsd"),ObjectId("badsfds")]等)的陣列
const query = {
"$expr": {
$and: [{
"$eq": ["$appId",req.user.appId],
}]
}
}
query['$expr']['$and'].push({
$or: [
{
$in: [
"$targetFrom",
bb
]
},
{
$in: [
"$targetTo",
bb
]
}
]
})
編輯:要求已更新:獲取具有特定 的所有 objs appId,其中一個targetFrom或是targetTo給定陣列之一,并且date介于給定startDate和之間endDate:
單人游樂場
在上面的 mongoplayground 中,我正在獲取appId"1"、startDateis 2022-01-01、endDateis2022-01-31和 bb 為 ["a","c","x"] 的所有物件。這應該獲取所有 3 個檔案,但日期會過濾掉第三個檔案,因為該date檔案中的2021-12-24. 如果您在此之前更改日期,您將獲得全部 3 個。
const query = {
"$expr": {
$and: [{
"$eq": ["$appId",req.user.appId],
}]
}
}
query['$expr']['$and'] = query['$expr']['$and'].concat([{
$and: [
{
$gte: [
"$date",
startDate
]
},
{
$lt: [
"$date",
endDate
]
}
]
},{
$or: [
{
$in: [
"$targetFrom",
bb
]
},
{
$in: [
"$targetTo",
bb
]
}
]
}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414142.html
標籤:
