我想做一个查询,我可以到达银行为banco1且投资额不等于“箱”的所有银行。
我该怎么做?我尝试了此查询,但不起作用:
db.banks.find({“投资”:{$ elemMatch:{银行:“ banco1”,productName:{$ ne:“ box}}}});
此查询是我尝试过的许多示例之一。
谢谢。
{
"_id": "5d3fc8c3914297c7b9a3a9e5",
"banco": "banco 1",
"investimentos": [{
"bank": "banco1",
"risk": "Conservador",
"expiryDate": "2021-10-04",
"tax": "1.02",
"discriminator": "investment",
"productName": "LCI"
},
{
"bank": "banco1",
"risk": "Conservador",
"expiryDate": "2020-06-24",
"tax": "0.75",
"discriminator": "investment",
"productName": "Fundo DI"
},
{
"bank": "banco1",
"risk": "Conservador",
"tax": "0.04",
"discriminator": "investment",
"id": "259ad8ac-57b7-4d33-8e75-46cf5c5c28e3",
"aniversary": "30",
"productName": "box"
}
}],
{
"_id": "5d3fcb4c914297c7b9a3a9e6",
"banco": "banco2",
"investimentos": [{
"bank": "banco2",
"risk": "Conservador",
"expiryDate": "2020-06-24",
"tax": "0.80",
"discriminator": "investment",
"id": "73db503f-c780-448c-a6a8-05d2837ff6ff",
"redemptionDate": "D+1",
"productName": "Fundo DI"
}
,
{
"bank": "banco2",
"risk": "Conservador",
"expiryDate": "2020-12-17",
"tax": "0.98",
"discriminator": "investment",
"id": "54e01515-dc7f-470f-8f00-8603c8f00686",
"productName": "LCA"
},
{
"bank": "banco2",
"risk": "Conservador",
"expiryDate": "2021-08-05",
"tax": "1.0",
"discriminator": "investment",
"id": "259ad8ac-57b7-4d33-8e75-46cf5c5c28e2",
"productName": "CDB"
}
}]
答案 0 :(得分:0)
欢迎来到SO Luan!
我发现Mongo Aggregations为我提供了find中所有可用的功能,以及更多的功能。因此,大约有95%的时间,除非我进行快速查询,否则最终都会汇总。
以下汇总将为您提供所需的信息:
db.getCollection('Test').aggregate([
{ $unwind: "$investimentos"},
{ $match: {
'investimentos.bank': "banco1",
'investimentos.productName': /^(?!box$)/
}},
])
$unwind管道采用了investimentos中的嵌入式文档数组,并创建了一个新文档,保留了带有investimentos的每个元素的父字段(_id和banco)。您可以尝试db.getCollection('Test').aggregate([{ $unwind: "$investimentos"}])
直观地看到会发生什么。
$match管道与find方法具有相同的作用-给它提供要应用的过滤器列表。第二个元素使用正则表达式(用'/'字符包围)指定它应查找所有不以“ box”开头的内容。