I have got two collections in MongoDB:
User collection:
{
  id : 1,
  name : "John",
  username : "Ricky1",
}
Post collection:
{
 id : 1,
 title : "mongodb collections",
 userİd : 1,
}
How do I merge these two collections?
I have got two collections in MongoDB:
User collection:
{
  id : 1,
  name : "John",
  username : "Ricky1",
}
Post collection:
{
 id : 1,
 title : "mongodb collections",
 userİd : 1,
}
How do I merge these two collections?
 
    
     
    
    I don't think it can be done. You will need to do 2 queries:
One to find the user, and another to get all posts filtering by that userId.
 
    
     
    
    for all posts by username "Ricky1":
db.post.find({userId:db.user.findOne({"username" : "Ricky1"}).id});
Maybe helps a little. The mongo way to do this, though, I gather, would be to have collections of posts nested inside each user in your users collection.
 
    
    Here Example Inner Join
db.users.aggregate({ $lookup: {
from : "courses", 
localField: "courseId", 
foreignField: "_id",
 as : "usersInCourse"}}
,{ $match : { "usersInCourse" : { $ne : []}}})
Above MongoDB Query Output
{
  _id: ObjectId("643404232a8430b9d86ec42b"),
  name: 'Ishan',
  isVerified: true,
  courseId: [
    ObjectId("643402ebae34b1cbab3bb377")
  ],
  usersInCourse: [
    {
      _id: ObjectId("643402ebae34b1cbab3bb377"),
      CourseName: 'MongoDB Basics',
      price: 50
    }
  ]
},{
  _id: ObjectId("643404232a8430b9d86ec42c"),
  name: 'Bhavesh',
  isVerified: true,
  courseId: [
    ObjectId("643402ebae34b1cbab3bb377"),
    ObjectId("643402ebae34b1cbab3bb378")
  ],
  usersInCourse: [
    {
      _id: ObjectId("643402ebae34b1cbab3bb377"),
      CourseName: 'MongoDB Basics',
      price: 50
    },
    {
      _id: ObjectId("643402ebae34b1cbab3bb378"),
      CourseName: 'NodeJS',
      price: 50
    }
  ]
}
In users collection data
{
  _id: ObjectId("643404232a8430b9d86ec42b"),
  name: 'Ishan',
  isVerified: true,
  courseId: [
    ObjectId("643402ebae34b1cbab3bb377")
  ]
},
{
  _id: ObjectId("643404232a8430b9d86ec42c"),
  name: 'Bhavesh',
  isVerified: true,
  courseId: [
    ObjectId("643402ebae34b1cbab3bb377"),
    ObjectId("643402ebae34b1cbab3bb378")
  ]
},
{
  _id: ObjectId("64340835ae34b1cbab3bb38c"),
  name: 'Amol',
  isVerified: true,
  courseId: []
}
In courses collection data
{
  _id: ObjectId("643402ebae34b1cbab3bb378"),
  CourseName: 'NodeJS',
  price: 50
},
{
  _id: ObjectId("643402ebae34b1cbab3bb377"),
  CourseName: 'MongoDB Basics',
  price: 50
}
