Mongodb 如何将文档中的数组元素投影到特定位置
我有一份这样的文件 {“_id”:ObjectId(“5c6cc08a568f4cdf7870b3a7”) “电话”:{ “单元格”:[ "854-6574-545", "545-6456-545" ], “主页”:[ "5474-647-574", "455-6878-758" ] } } 我想这样显示输出。 输出 请注意。用于从阵列中投影编号 查询:Mongodb 如何将文档中的数组元素投影到特定位置,mongodb,Mongodb,我有一份这样的文件 {“_id”:ObjectId(“5c6cc08a568f4cdf7870b3a7”) “电话”:{ “单元格”:[ "854-6574-545", "545-6456-545" ], “主页”:[ "5474-647-574", "455-6878-758" ] } } 我想这样显示输出。 输出 请注意。用于从阵列中投影编号 查询: db.collection.find({}, { "phone.cell": { $slice: 1 }, "phon
db.collection.find({},
{
"phone.cell": {
$slice: 1
},
"phone.home": 0
})
{
"_id": ObjectId("5c6cc08a568f4cdf7870b3a7"),
"phone": {
"cell": [
"854-6574-545"
]
}
}
db.collection.find({},
{
"_id": 0,
"phone.cell": {
$slice: 1
},
"phone.home": 0
})
结果:
db.collection.find({},
{
"phone.cell": {
$slice: 1
},
"phone.home": 0
})
{
"_id": ObjectId("5c6cc08a568f4cdf7870b3a7"),
"phone": {
"cell": [
"854-6574-545"
]
}
}
db.collection.find({},
{
"_id": 0,
"phone.cell": {
$slice: 1
},
"phone.home": 0
})
查询2:
db.collection.find({},
{
"phone.cell": {
$slice: 1
},
"phone.home": 0
})
{
"_id": ObjectId("5c6cc08a568f4cdf7870b3a7"),
"phone": {
"cell": [
"854-6574-545"
]
}
}
db.collection.find({},
{
"_id": 0,
"phone.cell": {
$slice: 1
},
"phone.home": 0
})
结果2:
{
**最终查询-使用聚合**
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"
]
}
}
错误:错误:{“确定”:0,“errmsg”:“投影不能同时包含和排除。”,“代码”:2,“代码名”:“BadValue”}这是我遇到的错误。我们不能同时包含同一输出字段的include和exclude。您使用mongo shell吗?如果是,版本是什么?指定其他版本。我已经用mongo shell版本4.0.4测试过了。您可以发布您正在运行的查询吗?succes query db.loandetails.find({},{''''''''phone.cell':{$slice:1},“phone.home”:0}).pretty()错误查询db.loandetails.find({},{'''u id':1,'phone.cell':{$slice:1},“phone.home”:0})。pretty()如果集合有其他字段,即使我没有在项目中指定id,也会默认返回。无需显式传递它