我有两个名为collection1collection2的集合,它们的 struct 如下,

//集合1

[
  { "_id": 100, "text": "i am good", "history":[{"date":"2023-6-1", "updated":"2023-6-2"}] },
  { "_id": 101, "text": "i am naughty"}
]

//集合2

[
  { "_id": 1,collection1Id:100, "date":"2023-6-1", "updated":"2023-6-2" },  // is present in 1 so should not goto this collection
  { "_id": 2,collection1Id:101, "date":"2023-7-3", "updated":"2023-7-5" }
]

我希望运行聚合查询,以便如果collection1内不存在字段(history),则应该查找collection2.请参阅下面的代码:

db.collection1.aggreagte([

if history is not exist in collection1
{
lookup from collection2
}

])

Expected Output

在执行聚合之后,我希望结果如下所示:

[
  { "_id": 100, "text": "i am good", "history":[{"date":"2023-6-1", "updated":"2023-6-2"}] },
  { "_id": 2,"text": "i am naughty", "history":[{"_id": 2, collection1Id: 101, "date":"2023-7-3", "updated":"2023-7-5"}],  } // history has been taken from collection 2 
]

第一行来自collection1,只是因为历史记录存在,第二行记录来自collection2,我在其中查找到history字段,因为主集合中不存在history字段.

推荐答案

我不认为有条件的$lookup加入另一个Collection 是可能的.

但是,如果缺少history字段,则可以创建history字段,然后为其赋值collection2.否则,保持其现有价值.

db.collection1.aggregate([
  {
    "$lookup": {
      "from": "collection2",
      "localField": "_id",
      "foreignField": "collection1Id",
      "as": "collection2"
    }
  },
  {
    $set: {
      history: {
        "$cond": {
          "if": {
            $eq: [
              {
                $type: "$history"
              },
              "missing"
            ]
          },
          "then": "$collection2",
          "else": "$history"
        }
      }
    }
  },
  {
    $unset: "collection2"
  }
])

Demo @ Mongo Playground

Mongodb相关问答推荐

MongoDB—基于数组中同一文档中的另一个字段更新字段

为什么AllowDiskUse不能在$GROUP阶段的聚合管道中工作?

最有效的Mongo聚合来展开和过滤:匹配、展开、匹配与投影和过滤

在mongdob中按子文档筛选不起作用

Mongo查找条件:不存在

如何对 MongoDB setWindowFields 中当前文档以外的文档进行操作

mongodb:多键索引 struct ?

NodeJS + MongoDB:使用 findOne () 从集合中获取数据

增加嵌套对象中的值?

根据 Month 删除 mongodb 中的旧记录

如何使用 C# MongoDB 驱动程序检索字段子集?

Mongoose 与 mongodb 如何返回刚刚保存的对象?

Clojure 和 NoSQL 数据库

Mongoose 的保存回调是如何工作的?

Mongo聚合框架,排序然后分组不起作用

在 MongoDB 中快速搜索数十亿个小文档的策略

未找到 MongoDB 数据/数据库

带有索引字段的 MongoDB 正则表达式

用 MongoDB 中的属性表示多对多关系的最佳模型

MongoDB Compass timeouts超时