K.  _ K. _ - 4 months ago 13
Node.js Question

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

This is a collection called

test
.

{
{"_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
    groupName
    are "A".

  2. whose
    lastModified
    are not the greatest value(
    ISODate("2016-01-10T23:25:56.314Z")
    ) of the
    lastModified
    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
node-mongodb-native
module.
Can I do it without fetching and iterating over the entire documents? I mean, can I do it within DB?

Answer

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.

Comments