Skip to content

Instantly share code, notes, and snippets.

@npentrel
Created August 3, 2018 21:20
Show Gist options
  • Save npentrel/d1a8dad4aa8508a7d89f9febffacb516 to your computer and use it in GitHub Desktop.
Save npentrel/d1a8dad4aa8508a7d89f9febffacb516 to your computer and use it in GitHub Desktop.
Use aggregation expressions in queries with $expr - insert, create index, and find queries
> db.accountsWithDate.insertMany([
   {"_id": 1, "credits": 5000, "expenses": [2000, 2000], "date": new ISODate("2018-05-01T12:42:10.318Z")},
   {"_id": 2, "credits": 4000, "expenses": [1000, 4000, 2000], "date":  new ISODate("2018-05-01T22:21:50.015Z")},
   {"_id": 3, "credits": 3000, "expenses": [1500, 750], "date": new ISODate("2018-05-02T07:01:20.259Z")},
   {"_id": 4, "credits": 2000, "expenses": [2500, 750], "date": new ISODate("2018-05-03T16:39:05.120Z")}
 ]) 
> db.accountsWithDate.createIndex({"date": 1})
> db.accountsWithDate.find({
     date: {$gte: ISODate("2018-05-01T00:00:00.000Z"),
            $lt: ISODate("2018-05-02T00:00:00.000Z")},
     $expr : {
         $gt : [
             { $sum : ["$expenses"] },
             "$credits"
         ]
     }
 })
{ "_id" : 2, "credits" : 4000, "expenses" : [ 1000, 4000, 2000 ], "date" : ISODate("2018-05-01T22:21:50.015Z") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment