Simple Querying & Aggregation Of MongoDB Collections

Return all documents where one element in the array of likes is ‘burgers’

db.mongo.find({Likes : “burgers”}).forEach(printjson)

Return documents where name includes, using Regex

Here, we can use:

  • FindOne() which returns the first document it finds
  • Find() which returns all documents matching that criteria

db.mongo.findOne({“name”:{$regex:”.*Kimi.*”}})

db.mongo.find({“name”:{$regex:”.*Kimi.*”}})

Return documents where field greater than X

db.mongo.find({Age : {$gt:50}}).forEach(printjson)

Using unwind to aggregate

To explode an array, we can use: db.mongo.aggregate( [ { $unwind : “$Likes” } ] )

We use this in conjunction with grouping to count the number of occurrences of each item within the array.

db.mongo.aggregate({$unwind:”$Likes”},{ $group: { _id: “$Likes”, count: { $sum: 1 } } })

Taking average of one field within array

Here, we unwind the array as above, and then take the average of a field within the array.

db.mongo.aggregate(
{$unwind : “$size”},
{$group : {_id : null,
“avgH” :{$avg : “$size.h”},
“avgW” :{$avg : “$size.w”}
} } )

Count the occurrences of a specific field value

db.mongo.count({“Likes”:”burgers”})

Multiple where conditions

db.mongo.find({$and:[{Age : {$gt:50}}, {Age : {$lt:100}}]})

Share the Post:

Related Posts