抱歉,如果該問題已被提出,但我無法真正找到針對我的特定問題的解決方案。
假設我有多個集合:
// 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',
}
}
如您所見,這兩個集合的資料非常相似。是否可以將集合分開,但在查詢時將它們全部回傳?
例如,是否可以按日期對兩個集合的檔案進行排序并在單個查詢中獲取前 10 個?
如果不可能,我應該只做一個集合并將兩種檔案都放在那里嗎?使用貓鼬并具有預定義模式時是否可以這樣做?
uj5u.com熱心網友回復:
$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>
解釋:
- 在第一個專案階段,我們僅從 col1 集合中過濾日期欄位。
- 在第二階段,我們從 col2 集合中添加日期
- 在管道中,我們按降序對結果進行排序
- 在最后一個流水線階段結果僅限于前 10 個
游樂場示例
uj5u.com熱心網友回復:
$unionWith- 合并來自兩個集合的檔案$sort- 按日期對檔案進行排序$limit- 僅回傳前 10 個檔案
db.collection_1.aggregate([
{
"$unionWith": {
"coll": "collection_2"
}
},
{
"$sort": {
"date": -1
}
},
{
"$limit": 10
}
])
作業示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414147.html
標籤:
