Mongodb 使用聚合合并两个单独集合的记录

Mongodb 使用聚合合并两个单独集合的记录,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,我有两个独立的收藏,比如说collA和collB。这两个集合都有一些公共字段,比如fieldA、fieldB、fieldC db.getCollection('collA').aggregate([ { "$match":{ // Some filter condition } }, { "$project":{ "_id":1, "fieldA":1,

我有两个独立的收藏,比如说collA和collB。这两个集合都有一些公共字段,比如fieldA、fieldB、fieldC

db.getCollection('collA').aggregate([
    {
        "$match":{
            // Some filter condition
        }
    },
    {
        "$project":{
            "_id":1,
            "fieldA":1,
            "fieldB":1,
            "fieldC":1
        }
    }
]);
假设我从科拉那里得到10张唱片

db.getCollection('collB').aggregate([
    {
        "$match":{
            // Some filter condition
        }
    },
    {
        "$project":{
            "_id":1,
            "fieldA":1,
            "fieldB":1,
            "fieldC":1
        }
    }
]);
假设我从collB那里得到5条记录

现在,我想做的是合并这15条记录,并执行其他聚合操作,如$group和其他许多操作

有没有办法通过mongoDB聚合或任何其他替代选项做到这一点

假设这两个集合的架构如下

CollA
{
    fieldA : String,
    fieldB : String
    fieldC : String
    fieldD : String
}


CollB
{
    fieldA : String,
    fieldB : String
    fieldC : String
    fieldE : String
}

你可以在下面试试

在这里,首先您需要放置以从聚合集合中获取单个文档。。。然后在同一组输入文档的单个阶段中处理多个聚合管道。。。现在需要执行聚合以从限制为5和10的其他集合获取数据。。。从使用中提取两个数组,然后简单地将其替换为新的根
data
using


他们有数据库参考吗?Col1和Col2?使用聚合查询两个集合的唯一方法是,它们是否具有db REF?能否发布所有集合的日志here@CaptainJackSparrow不,它们之间没有db引用。@AnthonyWinzlet我已用架构更新了描述
db.collection.aggregate([
  { "$limit": 1 },
  { "$facet": {
    "collectionA": [
      { "$lookup": {
        "from": Collection.name,
        "pipeline": [
          { "$limit": 5 }
        ],
        "as": "collectionA"
      }},
      { "$project": { "collectionA": 1, "_id": 0 }},
      { "$unwind": "$collectionA" },
      { "$replaceRoot": { "newRoot": "$collectionA" } }
    ],
    "collectionB": [
      { "$lookup": {
        "from": Collection.name,
        "pipeline": [
          { "$limit": 10 }
        ],
        "as": "collectionB"
      }},
      { "$project": { "collectionB": 1, "_id": 0 }},
      { "$unwind": "$collectionB" },
      { "$replaceRoot": { "newRoot": "$collectionB" } }
    ]
  }},
  { "$project": {
    "data": {
      "$concatArrays": [ "$collectionA", "$collectionB" ]
    }
  }},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" } }
  // Here you can perform your other operations //
])