簡體   English   中英

MongoDB 數組對象中的聚合搜索 [nodejs, mongoose]

[英]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]
        }],
    }
}

mongoplayground

所以,我需要使用$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.

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