如何从用户集合中按ID选择电子邮件,如下所示:
select emailAddress from users where _id="***"
我在mongo中选择它,但结果不正确
db.getCollection('users').find({_id: "QYoHQkTuTXnEC6Pws"},{ "emails.0.address": 1})
已更新:示例文件
{
"_id": "QYoHQkTuTXnEC6Pws",
"createdAt": ISODate("2017-03-09T06:21:29.664Z"),
"emails": [{
"address": "x@gmail.com",
"verified": true
}],
"isDeleted": false
}
答案 0 :(得分:3)
查看您的查询,您希望只查找给定ID的第一封电子邮件和地址字段。根据预期的输出,您可以尝试以下查询并选择。
会给你所有地址
db.users.find({_id:'QYoHQkTuTXnEC6Pws'}, { "emails.address": 1})
响应
{
"_id" : "QYoHQkTuTXnEC6Pws",
"emails" : [
{
"address" : "x@gmail.com"
},
{
"address" : "x2@gmail.com"
}
]
}
只会向您提供阵列中的第一个电子邮件地址。您已明确删除所有其他字段
db.users.find({_id:'QYoHQkTuTXnEC6Pws'},
{ 'emails.verified':0, _id:0, createdAt: 0, isDeleted: 0, "emails": {$slice: 1}})
响应
{
"emails" : [
{
"address" : "x@gmail.com"
}
]
}
或者,您可以使用聚合来获得预期结果
db.users.aggregate({$match: {_id:'QYoHQkTuTXnEC6Pws'}},
{$project: {_id:0,email: {$arrayElemAt: ['$emails.address',0]}}})
响应
{"email" : "x@gmail.com"}
答案 1 :(得分:1)
我得到了你的要求的答案;
db.inventory.aggregate([{
$match: {
_id: "QYoHQkTuTXnEC6Pws"
}
}, {
$unwind: "$emails"
}, {
$replaceRoot: {
newRoot: "$emails"
}
}, {
$project: {
address: 1
}
}])
首先匹配正确的文档,然后$unwinds
emails
字段以显示内部对象,然后将根移动到它以使焦点靠近address
字段,然后{{ 1}}仅获取$project
,这会导致您的示例数据(包含多封电子邮件);
address