簡體   English   中英

MongoDB/Mongoose 查詢:如何根據字段值獲取不同的數據集

[英]MongoDB/Mongoose query: How to get different sets of data based on a field's value

我將nodejsnodejs庫一起用於我的 mongoDB 交互。

我正在構建一個登陸頁面查詢(想想 Netflix 頁面),需要為每個類別(想想喜劇、恐怖、戲劇……)獲得大約 15 個結果。

為每個“類別”發送查詢並處理回調問題以及對數據庫進行簡單頁面加載的大量請求似乎不是一個很好的解決方案......如下圖所示:

const categories = ['horror','drama','comedy']
let counterCallback = 0
let allShows = []
categories.map(category =>{
    Show.find({category: category},{limit: 15}, (err, shows)=>{
       if(shows){ allShows.push(shows)}
       allShows++
       if(allShows === categories.length){ return res.json(allShows) }
    })
})

我在想也許提出一個$or請求,但我不能限制每個“或”的數量......

const categories = ['horror','drama','comedy']
Show.find({
    $or:categories.map(category=> {return {category: category} })
},{limit: 10})

如何實現限制每個“類別”結果數量的請求?

謝謝

您可以利用 MongoDB 的聚合框架來運行復雜查詢,請嘗試以下查詢:

var categories = ['horror', 'comedy', 'drama']

Show.aggregate([
    /** This $match would help to  limit docs to particular categories, as each pipeline in facet stage has to iterate to all docs in collection for thrice as 3 categories given, So at least limiting docs to needed categories. */
    { $match: { category: { $in: categories } } }, 
    {
        $facet: {
            'horror': [{ $match: { category: 'horror' } }, { $limit: 1 }],
            'comedy': [{ $match: { category: 'comedy' } }, { $limit: 1 }],
            'drama': [{ $match: { category: 'drama' } }, { $limit: 1 }]
        }
    }])

測試: MongoDB-Playground

或者,您也可以使用$group來實現:

Show.aggregate([
    { $match: { category: { $in: categories } } },
    { $group: { _id: '$category', shows: { $push: '$$ROOT' } } },
    { $project: { category: '$_id', _id: 0, shows: { $slice: ['$shows', 1] } } },
    /** Below two stages are optional  */
    { $group: { _id: '', data: { $push: '$$ROOT' } } },
    { $project: { _id: 0 } }
])

測試: MongoDB-Playground

您可以將 MongoDB 聚合框架與$group操作一起使用。

我假設你有 MongoDB v4.2。 對於早期版本,使用{$ReplaceRoot:{newRoot:"$data"}} {$replaceWith:"$data"}代替{$replaceWith:"$data"} {$ReplaceRoot:{newRoot:"$data"}}

Show.aggregate([
  {
    $match: {
      category: {
        $in: [
          "horror",
          "comedy",
          "drama"
        ]
      }
    }
  },
  {
    $group: {
      _id: "$category",
      data: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $addFields: {
      data: {
        $slice: [
          "$data",
          15
        ]
      }
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceWith: "$data"
  }
]).exec((err, shows) => {
    if (err) throw err;
    console.log(shows);
})

蒙戈游樂場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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