Get data from two collection from first collection(test1) all data and from second collection (test2) customer name using createdBy and updatedBy from test1 collection.
In createdBy and updatedBy I want fullname from test2 collection:
Test1 collection:
{
"_id": "kcXtyaB7jGPw9Ks",
"dateCreated": "2022-07-12T13:09:16.270Z",
"dateModified": "2022-07-12T13:09:16.270Z",
"data1": 1,
"data2": 100,
"data3": 5,
"createdBy": "xQQrzRgi8",
"updatedBy": "56sgAeKfx"
}
Test2 collection:
{
"_id": "xQQrzRgi8",
"fullName": "test name created"
},
{
"_id": "56sgAeKfx",
"fullName": "test name update"
}
Response be like:
{
"_id": "kcXtyaB7jGPw9Ks",
"dateCreated": "2022-07-12T13:09:16.270Z",
"dateModified": "2022-07-12T13:09:16.270Z",
"data1": 1,
"data2": 100,
"data3": 5,
"createdBy": "test name created",
"updatedBy": "test name update"
}
2
Answers
I solved my query with below mongo query:
Here is Solved query https://mongoplayground.net/p/7Ekh-q8tkTy
If I’ve understood correctly, you can use $lookup like this:
This query do a "join" between "Test1" and "Test2" using
updatedBy
and_id
fields.And after that get the first element in the result (I assume there were only one element because you are comparing with
_id
but if there is more than one you can use another way like$unwind
) to output the value.Edit: To get both values (created and updated) you can do a second
$lookup
.Now the query:
updatedBy
name from field_id
inTest2
.updatedBy
.createdBy
name from field_id
inTest2
.createdBy
.$project
to not outputresult
.Example here