我有一个包含如下文档的集合:
{
"_id": ObjectId("507f191e810c19729de860ea"),
"SubCollection": [{
"_id": ObjectId("55849c0002cee826cc67550a"),
"Timestamp": NumberLong(635717988841453845),
"IsValid": true
},
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"Timestamp": NumberLong(635717988830033174),
"IsValid": true
}]
}
public class RootEntity
{
public ObjectId Id { get; set; }
public List<SubEntity> SubCollection { get; set; }
}
public class SubEntity
{
public ObjectId Id { get; set; }
public long Timestamp { get; set; }
public bool IsValid { get; set; }
}
我需要创建一个 mongo 查询,该查询返回仅包含第一个子集合项的文档。但是,子集合需要首先通过 IsValid bool 过滤,然后按 Timestamp 排序。
到目前为止,我有一个查询返回包含第一个子集合项的文档,但我无法让它先对子集合进行排序,这可以实现吗?
这是我到目前为止的查询,请注意我使用的是 C# .NET MongoDB Driver v2.0:
var filter = Builders<TestFocusEntity>.Filter.And(
Builders<RootEntity>.Filter.Eq(x => x.Id, id),
Builders<TestFocusEntity>.Filter.ElemMatch(x => x.SubCollection, sub => test.IsValid == true));
var result = await collection.Find(filter)
.Sort(Builders<RootEntity>.Sort.Ascending("SubCollection.$.Timestamp"))
.Project<RootEntity>(Builders<RootEntity>.Projection.Slice(x => x.SubCollection, 0, 1))
.ToListAsync();
var rootDocument = result.SingleOrDefault();
var subDocument = rootDocument == null
? null
: rootDocument.SubCollection.SingleOrDefault();