Mongo aggregation pipeline with mongo unwind operator

Mongo aggregations

Working with mongo aggregation framework CRUD operations.

Agrregations are used for better performance. Let’s imagine I have a multi-level array

{
	"products": [{
		"foods": [{
			"name": "apple",
			"min_price": 10,
			"max_price": 1000
		}, {
			"name": "banana",
			"min_price": 1,
			"max_price": 1000
		}, {
			"name": "grapes",
			"min_price": 10,
			"max_price": 1000
		}, {
			"name": "orange",
			"min_price": 100,
			"max_price": 1000
		}]
	}]
}

Instead of fetching the entire collection, I would aggregate on the the same collection and return the needed information.

Mongo provides a function called `$unwind`. Using which you could detach the array, seperate the docs from array.

The result of the mongo unwind would produce

{
	"products":{
		"foods":{
			"name": "apple",
			"min_price": 10,
			"max_price": 1000
		}
	},
	"products":{
		"foods":{
			"name": "banana",
			"min_price": 1,
			"max_price": 1000
		}
	},"products":{
		"foods":{
			"name": "grapes",
			"min_price": 10,
			"max_price": 1000
		}
	},
	"products":{
		"foods":{
			"name": "orange",
			"min_price": 100,
			"max_price": 1000
		}
	}
}

On the unwinded result, you can apply $match function to fetch the needed information.

For example if you need to fetch all documents which have `min_price` greater than 1. Then the below function would do exactly the same.

db.foods.aggregate([   
        { $unwind : "$products" },
        { $unwind : "$products.foods" },
        { $match  : { "products.foods.min_price": {$gt:1}    }}
    ])

Leave a Reply

Your email address will not be published. Required fields are marked *