在匹配元素之后返回子文档数组元素



我有一个文档,基本上看起来像这样:

{
_id: ObjectId("5b980578db509b467960ef50"),
items: [
{
_id: ObjectId("5b980578db509b467960ef90"),
date: 2010-10-10T00:00:00.000Z
},
{
_id: ObjectId("5b980578db509b467960ef91"),
date: 2010-10-11T00:00:00.000Z
},
{
_id: ObjectId("5b980578db509b467960ef92"),
date: 2010-10-12T00:00:00.000Z
},
{
_id: ObjectId("5b980578db509b467960ef93"),
date: 2010-10-13T00:00:00.000Z
},
{
_id: ObjectId("5b980578db509b467960ef94"),
date: 2010-10-14T00:00:00.000Z
},
{
_id: ObjectId("5b980578db509b467960ef95"),
date: 2010-10-15T00:00:00.000Z
}
]
}

我正在尝试构造一个查询,我可以在我拥有的ObjectId之后获取所有Items(即ObjectId("5b980578db509b467960ef92")(。

我的查询结果应如下所示:

{
_id: ObjectId("5b980578db509b467960ef50"),
items: [
{
_id: ObjectId("5b980578db509b467960ef93"),
date: 2010-10-13T00:00:00.000Z
},
{
_id: ObjectId("5b980578db509b467960ef94"),
date: 2010-10-14T00:00:00.000Z
},
{
_id: ObjectId("5b980578db509b467960ef95"),
date: 2010-10-15T00:00:00.000Z
}
]
}

另外,我希望所有Items都位于给定Item的相应date值之后。

我目前正在使用双查询方法,其中我根据ObjectID获取匹配的Item,然后使用date值查找所有Items

有没有"更好"的方法在一个查询中做到这一点?

您可以使用$indexOfArray查找匹配元素的索引,并使用$slice获取从匹配索引到数组末尾的所有元素 3.4.本质上是获取最后一个元素,直到匹配索引。

db.colname.aggregate([
{"$project":{
"items":{
"$slice":[
"$items",{
"$multiply":[
{"$subtract":[
{"$size":"$items"},
{"$add":[{"$indexOfArray":["$items._id",ObjectId("5b980578db509b467960ef92")]},1]}
]},
-1
]
}
]
}
}}
])

最新更新