MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Aggregation pipeline

My database is a collection of items on ebay. I want to list the number of related items with a certain item. I only want the number of related items as the answer. So far i have the code as shown below which gives me an error. Could someone please help me.

Hey @Jain_Shah

I think you are looking for something like the following

db.getCollection("products").aggregate([
	{ $match: { product: "Stop Watch" } },
	{
		$group: {
			_id: { related: "$related", product: "$title" },
			count: { $sum: 1 }
		}
	}
]);

Hey @Jain_Shah

So the code I provided is just your code but with the syntax corrected.

I would need to see what your collection documents look like to attempt to write the aggregation pipeline fully.

Some general comments:

1.It is very hard to implement collection specific code from a screenshot as we have to type by hand sample documents. A straight plain ascii list of json documents is much more easier and faster to import in our server. Preferably within a pre html tag.

2.You write product called 'Stop Watch’ but I do not see any fields bearing a name close to product. If you had shown at least one document with the string ‘Stop Watch’ we could have infer the name of the field.

1 Like