我有一个这样的文件。
{“ _id”:ObjectId(“ 5c6cc08a568f4cdf7870b3a7”),
“电话”:{ “细胞” : [ “ 854-6574-545”, “ 545-6456-545” ], “家”:[ “ 5474-647-574”, “ 455-6878-758” ] } }
我想显示这样的输出。 输出
{
"_id" : ObjectId("5c6cc08a568f4cdf7870b3a7"),
"phone" : {
"cell" : [
"854-6574-545"
]
}
}
请咨询。
答案 0 :(得分: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"
]
}
}