如何在特定位置的文档中投影数组元素

问题描述 投票:0回答:1

我有这样的文件。

{“_ id”:ObjectId(“5c6cc08a568f4cdf7870b3a7”),

“phone”:{“cell”:[“854-6574-545”,“545-6456-545”],“home”:[“5474-647-574”,“455-6878-758”]}}

我想显示这样的输出。产量

{
        "_id" : ObjectId("5c6cc08a568f4cdf7870b3a7"),
        "phone" : {
                "cell" : [
                        "854-6574-545"
                         ]
        }
}

请指教。

mongodb
1个回答
1
投票

使用$slice从数组中项目编号。

查询:

db.collection.find({},
{
  "phone.cell": {
    $slice: 1
  },
  "phone.home": 0
})

结果:

{
    "_id": ObjectId("5c6cc08a568f4cdf7870b3a7"),
    "phone": {
      "cell": [
        "854-6574-545"
      ]
    }
  }

查询2:

db.collection.find({},
    {
      "_id": 0,
      "phone.cell": {
        $slice: 1
      },
      "phone.home": 0
    })

结果2:{

    "phone": {
      "cell": [
        "854-6574-545"
      ]
    }
  }

**最终查询 - 使用聚合**

db.collections.aggregate([{'$match':{'phone.cell':{'$exists':true}}},
{'$project':{'_id':1,'phone.cell':{$slice:['$phone.cell',1,1]}}}])

**输出**

{
    "_id" : ObjectId("5c6cc08a568f4cdf7870b3a7"),
    "phone" : {
        "cell" : [ 
            "545-6456-545"
        ]
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.