MongoDB- find document by id then group it with key


My Data-Structure looks like this:

[
  {
    "_id": "1",
    "title": "Yamaha",
    "data": "Sed ut perspiciatis",
    "type": "Bike"
  },
  {
    "_id": "2",
    "title": "Pulsar",
    "data": "Quis autem vel eum",
    "type": "Bike"
  },
  {
    "_id": "3",
    "title": "Tesla Model Y",
    "data": "because it is pleasure",
    "type": "Car"
  },
  {
    "_id": "4",
    "title": "Harley-Davidson",
    "data": "praising pain was born",
    "type": "Bike"
  },
  {
    "_id": "6",
    "title": "Mustang",
    "data": "non numquam eius",
    "type": "Car"
  },
  {
    "_id": "7",
    "title": "BMW",
    "data": "Man of Culture",
    "type": "Car"
  }
]

Now, From FrontEnd Users Can Search any of the item from database using their unique _id, Like this:

db.collection.find({_id: "3" })

Which returns the following:

[
  {
    "_id": "3",
    "data": "because it is pleasure",
    "title": "Tesla Model Y",
    "type": "Car"
  }
]

Question Part:

Now, Including the above-returned document, I also want to return those documents which have it’s the matching type value.


My Questions means that; if the user is finding any document with their particular _id. let’s suppose 3 then it should return the following:

Find the Item with their Unique _id and $group the type field Value

  [{
    "_id": "3",
    "title": "Tesla Model Y",
    "data": "because it is pleasure",
    "type": "Car"
  }
  {
    "_id": "6",
    "title": "Mustang",
    "data": "non numquam eius",
    "type": "Car"
  },
  {
    "_id": "7",
    "title": "BMW",
    "data": "Man of Culture",
    "type": "Car"
  }]

Is that possible to do? Is that possible to $group the document after finding By Id ?. I’ve tried many ways but none of them are useful. Any Suggestions Guys?

Hello @Vishal_Sharma

Since you asked, I suppose you want to do it in one database hit
Is aggregation framework an option?

You could start with something like:

db.collection.aggregate(
[
	{
		"$match" : {
			"_id" : "3"
		}
	},
	{
		"$lookup" : {
			"from" : "collection",
			"localField" : "type",
			"foreignField" : "type",
			"as" : "related"
		}
	}
] )

It is not the exact format that you which but it is a good start since you get:

{
	"_id" : "3",
	"title" : "Tesla Model Y",
	"data" : "because it is pleasure",
	"type" : "Car",
	"related" : [
		{
			"_id" : "3",
			"title" : "Tesla Model Y",
			"data" : "because it is pleasure",
			"type" : "Car"
		},
		{
			"_id" : "6",
			"title" : "Mustang",
			"data" : "non numquam eius",
			"type" : "Car"
		},
		{
			"_id" : "7",
			"title" : "BMW",
			"data" : "Man of Culture",
			"type" : "Car"
		}
	]
}

You could $unwind the field related and make sure you remove _id:3. But personally, I try to work with the data as-is rather than putting more work on the server. It is as easy, if not more easy, to manipulate the result like above in the application rather than having a more complex pipeline.

2 Likes