0

我的文档看起来像这样

{
  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的第一个、第二个或最后一个文档的字段来获得排序的文档?nested_documents如果是,那我该怎么做?

4

2 回答 2

1

很抱歉打扰这个问题。我意识到有一个位置运算符可用于查询数组,因此在排序时尝试了该运算符并且它起作用了。

它可以通过使用位置运算符来完成。这就是我从外壳中做到的

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
于 2012-08-03T17:19:42.057 回答
1

您可以使用位置运算符按​​数组中的特定索引进行排序:

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);
于 2012-08-03T17:31:31.140 回答