我是Mongo的新手,我正在尝试从find()查询中检索具有相同名称的几个特定数据:
让我解释一下 - > 用户是具有以下文档的集合:
"linkedaccounts": [
{
"accountname": "Rani Charan",
"accountnumber": "10815748690065",
"ifsc": "UTIB0001081",
"virtualid": "taran@xyz",
"_id": "571488b9720023940539959e",
"isDefaultReceiving": false,
"isDefaultFunding": false,
"isAppEnabled": false,
"aeba": false,
"accountsource": 0
},
{
"accountname": "Rani Singh",
"accountnumber": "01316366360080",
"virtualid": "ranisingh@xyz",
"_id": "571488b972002394053995a0",
"ifsc": "UTIB0000131",
"isDefaultReceiving": false,
"isDefaultFunding": true,
"isAppEnabled": true,
"aeba": false,
"accountsource": 0
},
{
"accountname": "Rani K Singh",
"accountnumber": "07916956560873",
"virtualid": "ranik@xyz",
"_id": "571488b9720023940539959f",
"ifsc": "UTIB0000791",
"isDefaultReceiving": true,
"isDefaultFunding": false,
"isAppEnabled": true,
"aeba": false,
"accountsource": 0
}
]
现在我想获取虚拟身份证为“ranisingh @ xyz”的帐号和ifsc代码。我能够使用此查询获得一些过滤数据:
db.users.find(
{"linkedaccounts.virtualid": "ranik@xyz"},
{_id: 0, 'linkedaccounts.accountnumber': 1,'linkedaccounts.ifsc': 1})
但结果我得到所有三个帐号和ifsc代码。像这样: -
{
"linkedaccounts" : [
{
"accountnumber" : "10815748690065",
"ifsc" : "UTIB0001081"
},
{
"accountnumber" : "01316366360080",
"ifsc" : "UTIB0000131"
},
{
"accountnumber" : "07916956560873",
"ifsc" : "UTIB0000791"
}
]}
所以现在我想只打印一个帐号和ifsc代码,其中包含“ranisingh @ xyz”。
答案 0 :(得分:1)
你可以使用$ slice从数组中获取第一个元素:
db.users.aggregate([
{$unwind:"$linkedaccounts"},
{$match:{"linkedaccounts.virtualid":"ranik@xyz"}},
{$project:{
_id:0,
linkedaccounts:
{accountnumber:"$linkedaccounts.accountnumber",
ifsc:"$linkedaccounts.ifsc"}
}}
])
但要重塑文档,您需要使用这样的聚合:
convert score.jpg -rotate 90 -blur 0x2 -threshold 50% result.png
答案 1 :(得分:-2)
您可以使用“位置$运算符”使其仅返回匹配的子文档,而不是数组中的所有子文档。试试这个:
db.users.find(
{"linkedaccounts.virtualid": "ranik@xyz"} ,
{
_id: 0,
'linkedaccounts.$.accountnumber': 1,
'linkedaccounts.$.ifsc': 1
}
);
这应该只返回匹配的子文档,如下所示:
{
_id: ObjectId("564b16849408a50b00ec235e"),
"linkedaccounts" : [
{
"accountnumber" : "07916956560873",
"ifsc" : "UTIB0000791"
}
]
}
参考:https://docs.mongodb.org/manual/reference/operator/projection/positional/#proj.S
更新回复评论:这不起作用,因为此类查询仅限于使用位置$运算符。我建议改用聚合管道。