Skip to content

Instantly share code, notes, and snippets.

@ftao
Last active April 2, 2016 08:52
Show Gist options
  • Save ftao/85f4c594055591091febbdabf6337f0b to your computer and use it in GitHub Desktop.
Save ftao/85f4c594055591091febbdabf6337f0b to your computer and use it in GitHub Desktop.
express-mongo-aggregate-operation-in-pandas

Expression

see https://docs.mongodb.org/manual/meta/aggregation-quick-reference/#aggregation-expressions

Expressions

Arithmetic Expressions -> OK -> OK

Mongo Pandas
$and np.logical_and
$or np.logical_or
$not np.logical_not
$cmp combine of np.logical_not / == / <
$eq/$gt/$gte/$lte Series.eq/gt/lte/gte
$add/$div/.. Series.add
$concat Series.str.cat
$lower Series.str.lower
other string op

Project

row level operation

{ $project : { title : 1 , grade2 : {"$gt" : ["$grade", 1]}}}
df = df[:, ['title', 'grade']]
df['grade2'] = df['grade'] > 1
{ $project : 
  { title : 1, 
    isAdultMale : {
      $and : [{"$gt" : ["$age", "$age2"]}, {$eq : ["$sex" : "M"]}]
    }
  }
}
s = df[:, ['title', 'age', 'sex']]
s['isAdultMale'] = np.logical_and((s['age'] > s['age2']), (s['sex'] == "M"))
del s['age']
del s['sex']

if condition

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment