MongoDB 在另一个 table 中以匹配字段作为数组进行查找

MongoDB $lookup in another table with matching field as array

我正在尝试 return true false based value exists in array in other collection.

假设我的事件集合如下。

{"_id":{"$oid":"626aa83ca3d690ffe4a40103"},"name":"event1","title":"Event 1"}
{"_id":{"$oid":"626aa83ca3d690ffe4a40104"},"name":"event2","title":"Event 2"}
{"_id":{"$oid":"626aa83ca3d690ffe4a40105"},"name":"event3","title":"Event 3"}

我的用户合集如下:

{"_id":{"$oid":"62149d30950b000a31448eb3"},"userName":"dummy@username.com","commentDictionary":"{}","__v":0,"createdAt":{"$date":"2022-02-22T08:22:08.161Z"},"updatedAt":{"$date":"2022-04-27T07:11:58.999Z"},"passwordResetLinkExpiryDate":{"$date":"2022-03-22T16:40:15.356Z"},"_eventIds":[{"$oid":"626aa83ca3d690ffe4a40103"},{"$oid":"626aa83ca3d690ffe4a40105"}]}

根据用户集合中 _eventIds 中的匹配值,我正在寻找如下输出。这也在 userName 中,其值为 dummy@username.com

{"_id":{"$oid":"626aa83ca3d690ffe4a40103"},"name":"event1","title":"Event 1", attended: true}
{"_id":{"$oid":"626aa83ca3d690ffe4a40104"},"name":"event2","title":"Event 2", attended: false}
{"_id":{"$oid":"626aa83ca3d690ffe4a40105"},"name":"event3","title":"Event 3", attended: true}

我正在尝试使用 $lookup 但它需要一个匹配的键,但在我的例子中它是数组。所以无法理解这个逻辑。

查询

  • 查找适用于 single value/array,如果数组包含此值则匹配
  • 而不是做所有会更慢、更多内存等的查找,$limit 1被使用,因为我们只关心是否找到匹配项
  • if results are empty => attented = false else attended=true

Playmongo

Event.aggregate(
[{"$lookup": 
   {"from": "User",
    "localField": "_id",
    "foreignField": "_eventIds",
    "pipeline": [{"$limit": 1}],
    "as": "attended"}},
 {"$set": 
   {"attended": {"$cond": [{"$eq": ["$attended", []]}, false, true]}}}])