1

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.

1 Answer 1

2

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
      }
    ]
  }
]

mongoplayground

Sign up to request clarification or add additional context in comments.

1 Comment

Its better not to use the same ids. Add field "info" where you will store the id to another collection. Aggregation will be: "$lookup": { "from": "datas", "localField": "info", "foreignField": "_id", "as": "docs"}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.