$lookup 具有相同的集合

ror*_*oro 6 mongodb mongo-shell mongodb-query nosql-aggregation aggregation-framework

我是 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
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

我愿意接受任何建议。

Ash*_*shh 7

您可以在 mongodb 3.6及更高版本中尝试以下聚合

db.collection.aggregate([
  { "$match": { "Id": 2627 }},
  { "$lookup": {
    "from": "collection",
    "let": { "answerId": "$AnswerId" },
    "pipeline": [{ "$match": { "$expr": { "$eq": ["$Id", "$$answerId"] }}}],
    "as": "dates"
  }}
])
Run Code Online (Sandbox Code Playgroud)

3.4及以上

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