Reputation: 49
I have 2 collections:
Users:
"_id": {
"$oid": "62f7gsda96211065456322a10fe"
},
"name": "test",
"roles": ["user"],
"type": "user",
"fullName": "Test Test",
"email": "[email protected]",
"password_scheme": "pbkdf2",
"iterations": 10,
"derived_key": "ef150b4daa328703e68ae57f112321580ce95aa4",
"salt": "1e22243068bbsbsdva8d6459a683e2903",
"isDiactivated": false,
"idclient": {
"$oid": "60f7cca7321da11252a10fd"
}
Timelogs:
"_id": {
"$oid": "60f7ccbd62110611252a130a"
},
"dtstart": {
"$date": "2020-06-01T15:24:35.388Z"
},
"idstory": {
"$oid": "60f7ccad62110611252a1271"
},
"idworkday": {
"$oid": "60f7ccbd62110611252a1308"
},
"dtend": {
"$date": "2020-06-01T15:35:36.856Z"
},
"idclient": {
"$oid": "60f7cca7321da11252a10fd"
},
"idowner": {
"$oid": "62f7gsda96211065456322a10fe"
}
in the query I need to get timelogs. Timelogs has an "idowner" field that refers to users. I want to get all the data from timelogs, but also get the "name" of the user from the Users collection.
It should look like this:
"_id": {
"$oid": "60f7ccbd62110611252a130a"
},
"dtstart": {
"$date": "2020-06-01T15:24:35.388Z"
},
"idstory": {
"$oid": "60f7ccad62110611252a1271"
},
"idworkday": {
"$oid": "60f7ccbd62110611252a1308"
},
"dtend": {
"$date": "2020-06-01T15:35:36.856Z"
},
"idclient": {
"$oid": "60f7cca762110611252a10fd"
},
"idowner": {
"$oid": "62f7gsda96211065456322a10fe"
},
"name": "test"
Upvotes: 0
Views: 886
Reputation: 3900
You can use $lookup
to join 2 collections
db.timelogs.aggregate([{
$lookup: {
from: "user", //remote collection name
localField: "idowner.oid", //timelogs collection field
foreignField: "_id.oid", //remote collection mapping field
as: "idowner" //to be imported as
}
}
,{$unwind:"$idowner"}
,{$project:{
dtstart:1,
idstory:1,
idworkday:1,
dtend:1,
idclient:1,
idowner:"$idowner._id",
name:"$idowner.name"
}}
])
Upvotes: 1
Reputation: 81
db.timelogs.aggregate([{
$lookup: {
from: "user",
localField: "idowner.oid",
foreignField: "_id.oid",
as: "User"
}
}
,{$unwind:"$User"}
,{$project:{
'User':'$User.name'
])
Upvotes: 0