【问题标题】:Return subdocument array elements after matched element在匹配元素之后返回子文档数组元素
【发布时间】:2019-02-16 08:18:06
【问题描述】:

我的文档基本上是这样的:

{
    _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
        }
     ]
}

我正在尝试构建一个查询,我可以在其中获取所有Items我拥有的ObjectId(即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

有没有一种“更好”的方法可以在一个查询中做到这一点?

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-07-13
      • 2019-04-23
      • 2018-05-27
      • 2020-12-11
      • 2012-10-25
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      • 2016-10-31
      相关资源
      最近更新 更多