首页 > 解决方案 > 从嵌套数组中分页嵌入对象

问题描述

我对 mongodb 比较陌生,想知道是否可以查询下面的 BusinessDetails 集合,对于 _id: 6164bd360ab23b1482e1f10a 的业务,我可以分页其嵌入的客户对象,比如一次 10 个客户?

{
    "_id" : ObjectId("6164bd360ab23b1482e1f10a"),
    "name" : "Biz1",
    "user" : {
        "$ref" : "jhi_user",
        "$id" : "user-1"
    },
    "customers" : [ 
        {
            "$ref" : "customer_details",
            "$id" : ObjectId("6164bd150ab23b1482e1f109")
        }, 
        {
            "$ref" : "customer_details",
            "$id" : ObjectId("6164bd080ab23b1482e1f108")
        },
        {..},{..},{..}

    ],
    "_class" : "com.mycompany.seol.domain.BusinessDetails"
}

标签: mongodb

解决方案


您可以使用 $slice

db.collection.aggregate([
  {
    $match: {
      "_id": ObjectId("6164bd360ab23b1482e1f10a")
    }
  },
  {
    $addFields: {
      customers: {
        "$slice": [
          "$customers",
          0, // position
          1  // limit
        ]
      }
    }
  }
])

工作Mongo游乐场


推荐阅读