Mongodb 如何在嵌套文档数组的第一个或最后一个文档的字段上排序

Mongodb 如何在嵌套文档数组的第一个或最后一个文档的字段上排序,mongodb,Mongodb,我的文件看起来像这样 { field1: somevalue, field2: some other value, nested_documents: [ // array of nested document { ip: , session_id: , datetime: }, // first nested document { ip: , session_id: , datetime: }, // second nested document //

我的文件看起来像这样

{
  field1: somevalue,
  field2: some other value,


  nested_documents: [ // array of nested document
    { ip: , session_id: , datetime: }, // first nested document
    { ip: , session_id: , datetime: }, // second nested document

    // ...many more nested documents
  ]
},

是否可以根据嵌套文档数组的第一个、第二个或最后一个文档的
datetime
字段获取已排序文档?如果是,那么我该怎么做呢?

很抱歉打扰您了。我意识到有一个位置运算符可用于查询数组,所以在排序时尝试了该运算符,结果成功了

这可以通过使用“位置”操作符来完成。这就是我从贝壳里做的

sorting by the first nested document's field

   db.sample.find().sort({"nested_documents.0.field_name" : -1})   // for descending order sort

sorting by the second nested document's field

   db.sample.find().sort({"nested_documents.1.field_name" : -1})   // for descending order sort

Now for sorting by last document's field i have to keep track of length of the array so if length of array is 10 my query would be

   db.sample.find().sort({"nested_documents.9.field_name" : -1})   // for descending order sort
可以使用按数组中的特定索引进行排序:

db.foo.drop();

db.foo.insert({
    _id: 1,
    docs: [
        { date: new ISODate("2012-01-01T00:00:00Z") },
        { date: new ISODate("2010-01-01T00:00:00Z") }
    ]
});

db.foo.insert({
    _id: 2,
    docs: [
        { date: new ISODate("2011-01-01T00:00:00Z") },
        { date: new ISODate("2013-01-01T00:00:00Z") }
    ]
});

jsTest.log("Sorting by first embedded document's date, ascending");
db.foo.find({}, { "docs.date": 1 }).sort({"docs.0.date": 1}).forEach(printjson);

jsTest.log("Sorting by second embedded document's date, ascending");
db.foo.find({}, { "docs.date": 1 }).sort({"docs.1.date": 1}).forEach(printjson);

我没有从$elemMatch查询中获取
动态位置,无法进行排序
。我的错误。我的意思是引用,它允许您使用
$
引用原始查询中的字段进行更新。我之所以提出这个问题,是因为在另一个答案中提到了这个问题,后来被删除了。