簡體   English   中英

MongoDB 單查詢不同 collections

[英]MongoDB single query for different collections

抱歉,如果該問題已被提出,但我無法真正找到針對我的特定問題的解決方案。

假設我有多個 collections:

// collection 1 looks like this:
{
    fieldX: 'x',
    fieldY: 'y',
    date: '2022-01-15 12:00',
    condition: {
        enabled: true,
        condition: 'abc',
    }
}

// while collection 2 looks like this:
{
    fieldZ: 'z',
    date: '2022-01-15 15:25',
    condition: {
        enabled: false,
        condition: 'bce',
    }
}

如您所見,兩個 collections 的數據非常相似。 是否可以將集合分開,但在查詢時將它們全部返回?

例如,是否可以按日期對 collections 的文檔進行排序並在單個查詢中獲取前 10 個文檔?

如果不可能,我應該只做一個集合並將兩種文件都放在那里嗎? 使用 mongoose 並具有預定義架構時是否可以這樣做?

$unionWith操作從 mongodb 4.4 開始可用,類似於從 SQL 開始的 UNION ALL,例如:

   mongos> db.col1.aggregate([   
          { $project: { date: 1, _id: 0 } }, 
          { $unionWith: { coll: "col2",
          pipeline: [ {$project: { date: 1, _id: 0 } } ] }} ,
                     {$sort:{date:-1}} ,
                     {$limit: 10}
                    ])
  { "date" : "2022-01-15 15:25" }
  { "date" : "2022-01-15 12:00" }
  mongos> 

解釋:

  1. 在第一個項目階段,我們僅從 col1 集合中過濾日期字段。
  2. 在第二階段,我們從 col2 集合中添加日期
  3. 在管道中,我們按降序對結果進行排序
  4. 在最后一個流水線階段結果僅限於前 10 個

游樂場示例

  • $unionWith - 合並來自 collections 的文檔
  • $sort - 按日期對文檔進行排序
  • $limit - 只返回前 10 個文檔
db.collection_1.aggregate([
  {
    "$unionWith": {
      "coll": "collection_2"
    }
  },
  {
    "$sort": {
      "date": -1
    }
  },
  {
    "$limit": 10
  }
])

工作示例

暫無
暫無

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

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