1
[{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 6, createdAt:2018-11-30 20:49:52.855},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 1, createdAt:2018-11-30 20:49:52.855},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 8, createdAt:2018-11-30 20:49:52.855},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 5, createdAt:2018-11-30 20:49:52.855},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 5, createdAt:2018-11-30 20:49:52.855},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 5, createdAt:2018-11-30 20:49:52.855},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 3, createdAt:2018-11-30 20:49:52.855}]

Above is a snapshot of User Document. How can I find a user with least loginAttempts value. If same value is found for mutliple users then return one having creationDate value.

Saurabh Verma
  • 119
  • 2
  • 2
  • 11
  • possible duplicate of https://stackoverflow.com/questions/6360465/how-to-find-min-value-in-mongodb – Wyck Nov 30 '18 at 16:06

3 Answers3

0

Try the "sort and limit" technique.

db.users.find().sort({ loginAttempts: 1 }).limit(1)

Wyck
  • 10,311
  • 6
  • 39
  • 60
  • Hopefully it's logical how to extend this technique to apply more criteria such as your creationDate requirement. – Wyck Nov 30 '18 at 16:01
0

Maybe when you're querying the model you can use sort or order by.

db.col.find({category: A}).sort({loginAttempts: 1, createdAt: -1}).limit(1)

In follows the left to right order while sorting.

Or you can just loop through the array,

result.sort((a,b) => {
      return (a.loginAttempts - b.loginAttempts) || (b.createdAt - a.createdAt);
})[0]
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35
0

Using reduce and some ternary operators

var data = [{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 6, createdAt:"2018-11-30 20:49:52.855"},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 1, createdAt:"2018-11-30 20:49:52.855"},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 1, createdAt:"2018-11-11 20:49:52.855"},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 5, createdAt:"2018-11-30 20:49:52.855"},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 5, createdAt:"2018-11-30 20:49:52.855"},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 5, createdAt:"2018-11-30 20:49:52.855"},
{"_id":"5c0155a8407cf173d7ff01fa",loginAttempts : 3, createdAt:"2018-11-30 20:49:52.855"}]

smallest = data.reduce(function(prev, curr) {
    return prev.loginAttempts < curr.loginAttempts ? prev : curr.loginAttempts == prev.loginAttempts ? new Date(prev.createdAt) < new Date(curr.createdAt) ? prev : curr : curr;
});
console.log(smallest);
COLBY BROOKS
  • 331
  • 1
  • 5