简体   繁体   English

MongoDB 单查询不同 collections

[英]MongoDB single query for different collections

Sorry if the question has already been asked, but I cannot really find a solution for my particular problem.抱歉,如果该问题已被提出,但我无法真正找到针对我的特定问题的解决方案。

Let's say I have multiple 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',
    }
}

As you can see the two collections have data that is very similar.如您所见,两个 collections 的数据非常相似。 Is it possible to keep the collection separate, but when querying, to return them all together?是否可以将集合分开,但在查询时将它们全部返回?

For example, is it possible to sort the documents of both collections by date and get the first 10 in a single query?例如,是否可以按日期对 collections 的文档进行排序并在单个查询中获取前 10 个文档?

If it's not possible, shall I just make a single collection and put both kind of documents in there?如果不可能,我应该只做一个集合并将两种文件都放在那里吗? Is it possible to do when using mongoose and having a predefined schema?使用 mongoose 并具有预定义架构时是否可以这样做?

The $unionWith operation is available starting from mongodb 4.4, it is simlilar to UNION ALL from SQL, example: $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> 

explained:解释:

  1. In the first project stage we filter only date field from collection col1.在第一个项目阶段,我们仅从 col1 集合中过滤日期字段。
  2. In second stage we add the date from col2 collection在第二阶段,我们从 col2 集合中添加日期
  3. In the pipeline we sort the result in descending order在管道中,我们按降序对结果进行排序
  4. In last pipeline stage result is limited to first 10在最后一个流水线阶段结果仅限于前 10 个

playground example游乐场示例

  • $unionWith - To combine documents from both collections $unionWith - 合并来自 collections 的文档
  • $sort - To sort documents by date $sort - 按日期对文档进行排序
  • $limit - To return only the first 10 documents $limit - 只返回前 10 个文档
db.collection_1.aggregate([
  {
    "$unionWith": {
      "coll": "collection_2"
    }
  },
  {
    "$sort": {
      "date": -1
    }
  },
  {
    "$limit": 10
  }
])

Working example工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM