Skip to content

Instantly share code, notes, and snippets.

@matsimitsu
Last active February 1, 2017 15:26
Show Gist options
  • Save matsimitsu/29f98b1738e69217e07651861fa1b9c1 to your computer and use it in GitHub Desktop.
Save matsimitsu/29f98b1738e69217e07651861fa1b9c1 to your computer and use it in GitHub Desktop.
db.foo.insertMany([
{ email: 'wes@example.com', course: 'a', purchaseDate: 10 },
{ email: 'wes@example.com', course: 'b', purchaseDate: 20 },
{ email: 'wes@example.com', course: 'c', purchaseDate: 5 },
{ email: 'nancy@example.com', course: 'c', purchaseDate: 6 },
{ email: 'nancy@example.com', course: 'b', purchaseDate: 10 },
{ email: 'nancy@example.com', course: 'a', purchaseDate: 5 },
{ email: 'nancy@example.com', course: 'd', purchaseDate: 1 },
{ email: 'john@example.com', course: 'd', purchaseDate: 1 },
{ email: 'bob@example.com', course: 'a', purchaseDate: 1 }
])
db.foo.aggregate([
// Project the target purchasedate
{'$project': {
'email': 1,
'course': 1,
'purchaseDate': 1,
'target': { '$cond': [{'$eq': [ "$course", "a" ]}, "$purchaseDate", 0] }
}},
// Group records by email, storing the target and the highest encountered purchase date
{'$group': {
'_id': '$email',
'target': {'$max': '$target'},
'max': {'$max': "$purchaseDate"}
}},
// Check if the highest encountered date is greater then the target
{'$project': {
'email': 1,
'target':1,
'max': 1,
'selected': {'$cond': [{'$gt': ['$max', '$target']}, true, false] }
}},
// Filter out the non-matches
{'$match': {
'target': {'$gt': 0},
'selected': true
}},
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment