$查找相同的集合

$lookup with same collection

我是 MongoDB 的新手,所以我不确定我的问题表述是否正确。

我有一个集合,其中的数据如下所示:

{ 
    "_id" : ObjectId("66666"), 
    "Id" : 994, 
    "PostType" : 1, 
    "AnswerId" : 334, 
    "CreationDate" : ISODate("1994-09-05T09:34:36.177+0000"), 
    "Tags" : "test", 
    "Parent" : null, 
}

{ 
    "_id" : ObjectId("8888"), 
    "Id" : 334, 
    "PostTypeId" : 2, 
    "AnswerId" : NaN, 
    "CreationDate" : ISODate("20005-08-03T11:29:42.880+0000"), 
    "ParentId" : 994
}

两个文档都在同一个集合中,我正在尝试使用 PostType:1 文档中的 AnswerId,并使用该值作为主 ID 来提取其 CreationDate。

这是我试图实现的逻辑,但它似乎不起作用:

db.collection.aggregate([
    {$project:{_id:"$Id", Title:"$Title", Answerid:"$AnswerId", QuestionDate:"$CreationDate"}},
    {$match:{Id:"$Answerid"}},
    {$project:{AnswerDate:"$CreationDate"}}
])

我愿意接受任何建议。

您可以在 mongodb 3.6 及以上

中尝试以下聚合
db.collection.aggregate([
  { "$match": { "Id": 2627 }},
  { "$lookup": {
    "from": "collection",
    "let": { "answerId": "$AnswerId" },
    "pipeline": [{ "$match": { "$expr": { "$eq": ["$Id", "$$answerId"] }}}],
    "as": "dates"
  }}
])

3.4及以上

db.collection.aggregate([
  { "$match": { "Id": 2627 }},
  { "$lookup": {
    "from": "collection",
    "localField": "AnswerId",
    "foreignField": "Id",
    "as": "dates"
  }}
])