我有两个名为collection1
和collection2
的集合,它们的 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
字段.