K.  _ K. _ - 1 year ago 77
Node.js Question

MongoDB: how to query documents with `IS NOT(MAX())` criteria?

This is a collection called


{"_id": 1, "groupName": "A", lastModified: ISODate("2012-09-17T23:25:56.314Z")},
{"_id": 2, "groupName": "A", lastModified: ISODate("2013-09-17T23:25:56.314Z")},
{"_id": 3, "groupName": "A", lastModified: ISODate("2016-01-10T23:25:56.314Z")},
{"_id": 4, "groupName": "B", lastModified: ISODate("2020-09-17T23:25:56.314Z")},
{"_id": 5, "groupName": "B", lastModified: ISODate("2000-01-17T23:25:56.314Z")}

I want to query some documents within this collection, with these criteria:

  1. whose
    are "A".

  2. whose
    are not the greatest value(
    ) of the
    fields of the documents with
    "groupName": "A"

So in this case, the result should be

{"_id": 1, "groupName": "A", lastModified: ISODate("2012-09-17T23:25:56.314Z")},
{"_id": 2, "groupName": "A", lastModified: ISODate("2013-09-17T23:25:56.314Z")}

I'm using Node.js with
Can I do it without fetching and iterating over the entire documents? I mean, can I do it within DB?

Answer Source

If you'll definitely filter by groupName, this simple query can help you achieve your desired result without much performance overhead.

db.test.find({groupName : "A"}).skip(1).sort({lastModifiedAt : -1})

If you have a more complex scenario/grouping/nesting however, you might need to use aggregate or mapReduce framework.