I'm having two collections collection 'A' and 'B'
In collection 'A' I'm having fields:
Name, School, Class, Rank
In collection 'B' I'm having fields:
FatherName, MotherName, Location
How to add collection 'B' fields FatherName, MotherName, and Location to Collection 'A'
db.A.aggregate( [
{ $project: { _id: 0 } },
{ $merge : { into : "newCollection" } }
] )
This is not giving me derived result. Any better efficient result. Thank you.
CodePudding user response:
Every document has an _id
,
if you want _id
= 1 merge _id
= 1,
_id
= 2 merge _id
= 2
data
db={
"users": [
{
"_id": 1,
"Name": "almonds",
"School": "C",
"Class": "A",
"Rank": 2
}
],
"datas": [
{
"_id": 1,
"FatherName": "F",
"MotherName": "M",
"Location": "D"
}
]
}
aggregate
db.users.aggregate([
{
"$lookup": {
"from": "datas",
"localField": "_id",
"foreignField": "_id",
"as": "docs"
}
}
])
result
[
{
"Class": "A",
"Name": "almonds",
"Rank": 2,
"School": "C",
"_id": 1,
"docs": [
{
"FatherName": "F",
"Location": "D",
"MotherName": "M",
"_id": 1
}
]
}
]