简体   繁体   English

MongoDB:如何使用IS NOT(MAX())标准查询文档?

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

This is a collection called test . 这是一个称为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". groupName为“ 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" . lastModified 不是具有"groupName": "A"的文档的lastModified字段的最大值( ISODate("2016-01-10T23:25:56.314Z") )。

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. 我正在将Node.js与node-mongodb-native模块一起使用。 Can I do it without fetching and iterating over the entire documents? 我可以在不获取和迭代整个文档的情况下做到这一点吗? I mean, can I do it within DB? 我的意思是,我可以在DB中执行此操作吗?

If you'll definitely filter by groupName, this simple query can help you achieve your desired result without much performance overhead. 如果您一定要按groupName进行筛选,则此简单查询可以帮助您实现所需的结果,而不会增加性能开销。

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. 但是,如果您的场景/分组/嵌套更为复杂,则可能需要使用aggregatemapReduce框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM