Mohit Kumar
Mohit Kumar

Reputation: 5

Append fields from a document to other document having matching field MongoDB

I am trying to write MongoDB query to accomplish something which is explained below. I don't know whether it is possible in mongoDB or not. I know how to insert a field in single document or multiple document but my problem is little advance to that. I have a collection (say for "procs") having 5000 documents like:

{ "sid": 1 "procs": [ { "post_time": 0, "p_start": 1487303363.8170002, "pid": 1 }
] }

Here is the another document-2 from different collection(say for "acqs"):

{ "sn": 10302301, "date": "2017-12-11", "sid": 1 "acqs": [{ "aqid": 2, "aq_end": 1487305607.342 } ] } This collection also contains around 5000 documents.

Now i want to insert "sn" and "date" fields from document 2 to document 1 corresponding to same "sid" field values. so i want output something like this: { "sn": 10302301, "date": "2017-12-11", "sid": 1 "procs": [{ "post_time": 0, "p_start": 1487303363.8170002, "pid": 1 } ] }

Upvotes: 0

Views: 49

Answers (1)

Simran
Simran

Reputation: 2830

In mongoDb , you can use $lookup

db.procs.aggregrate([
   {
      $lookup:
        {
          from: "acqs",
          localField: "sid",
          foreignField: "sid",
          as: "procs_docs"
        }
   }

])

Result Will be like :

  { 
"sn": 10302301, "date": "2017-12-11", "sid": 1 ,
"acqs": [{ "aqid": 2, "aq_end": 1487305607.342 } ]
"procs_doc": ["sid": 1,procs:{ "post_time": 0, "p_start": 1487303363.8170002, "pid": 1 } ] }

If you are using mongoose then you can use populate method of mongoose ,which lets you reference documents in other collections.

Upvotes: 1

Related Questions