繁体   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