Lookup multiple collection with conditions

I have three collection: user, buyer, merchant, example below:

user:{
  _id
  userType: enum(BUYER, MERCHANT)
}

buyer:{
_id,
userId
}

merchant:{
_id,
userId
}

I want get user and detail of it then I using aggregate with lookup to two collection ( buyer and merchant). Now I want lookup only one collection with correct userType. Have any solution. My query below:

user.aggregate([
	{
		$lookup: {
			from: 'buyer',
			as: 'buyer',
			localField: '_id',
			foreignField: 'userId',
		},
	},
	{ $unwind: { path: '$buyer', preserveNullAndEmptyArrays: true } },
	{
		$lookup: {
			from: 'merchant',
			as: 'merchant',
			localField: '_id',
			foreignField: 'userId',
		},
	},
	{ $unwind: { path: '$merchant', preserveNullAndEmptyArrays: true } },
])

Thanks

Hi @V_Nguy_n_Van and welcome to MongoDB community forums!!

Could you please elaborate more on the above statement with some supporting information like:

  1. A sample document based on the above schema.
  2. The desired output from the above aggregation query.
  3. The MongoDB version you are on.

Generally, in MongoDB, data formation into the collection plays an important role while writing efficient and simpler queries.
I would highly recommend you to go through Data Modelling documentation for more clear understanding.

I am suggesting some resources that you can go through to expand your knowledge of MongoDB:
Introduction to MongoDB
Data Modelling Course
Data Model Design

Regards
Aasawari

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.