10

I am new to MongoDB so I am not sure if I have phrased my question correctly.

I have a collection in which data looks like this:

{ 
    "_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
}

Both documents are in the same collection, im trying to use the AnswerId from a document with PostType:1, and using that value as the main Id to extract its CreationDate.

Here's the logic im trying to implement, but it doesnt seem to be working:

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

I am open to any suggestion.

Ashh
  • 44,693
  • 14
  • 105
  • 132
roro
  • 713
  • 2
  • 6
  • 19
  • Could you explain what you want to achieve? – Ashh Oct 06 '18 at 01:18
  • I want to get the CreationDate from a document and use its AnswerId to get another CreationDate from a second document(using AnswerId as identifier) and then do some Date calculations. So for example, using the data above, I would get creation date for _Id:2627_ then use its _AnswerId: 2629_ as the _new Id_ to get CreationDate of second document. – roro Oct 06 '18 at 01:30

1 Answers1

13

You can try below aggregation in mongodb 3.6 and above

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

Or with the 3.4 and above

db.collection.aggregate([
  { "$match": { "Id": 2627 }},
  { "$lookup": {
    "from": "collection",
    "localField": "AnswerId",
    "foreignField": "Id",
    "as": "dates"
  }}
])
Ashh
  • 44,693
  • 14
  • 105
  • 132