我从 MongoDB 开始,所以,如果我的问题太基本,抱歉。我在 Mongo 中有一个集合,其结构如下:
{
nome: "Diego", contas: [
{
banco: "itau",
tipo: "corrente",
investimentos: [{
tipo: "fundo",
transacoes: [{
numero: 1,
valor: 1000,
data: "24/06/2017"
},
{
numero: 2,
valor: 1500,
data: "01/02/2017"
}]
},
{
tipo: "poupanca",
transacoes: [{
numero: 1,
valor: 600,
data: "20/06/2017"
}]
}]
},
{
banco: "bradesco",
tipo: "poupanca",
investimentos: []
},
{
banco: "santander",
tipo: "juridica",
investimentos: [{
tipo: "pic",
transacoes: [{
numero: 1,
valor: 100,
data: "20/06/2017"
},
{
numero: 2,
valor: 100,
data: "20/05/2017"
},
{
numero: 3,
valor: 100,
data: "20/05/2017"
}]
}]
}]
}
而我要的筛选investimentos
的阵列conta
,以包含仅在该领域的条目tipo
是等于fundo
。有我的查询:
db.teste.aggregate([
{
$project: {
nome: 1,
"contas.investimentos": {
$filter: {
input: "$contas.investimentos",
as: "investimento",
cond: { $eq: ["$$investimento.tipo", "fundo"]}
}
}
}
}]);
结果是:
{
"_id" : ObjectId("59563cf574f77220ff2166ea"),
"nome" : "Diego",
"contas" : [
{
"investimentos" : []
},
{
"investimentos" : []
},
{
"investimentos" : []
}
]
}
我无法理解为什么结果null
在 field 上investimentos
。我认为我处理子数组的方式有问题,但我找不到差距在哪里。有谁可以帮助我吗 ?
您必须使用$map
来映射contas
值并到达$filter
investimentos
.
就像是
db.teste.aggregate([{
$project: {
nome: 1,
contas: {
$map: {
input: "$contas",
as: "contas",
in: {
banco: "$$contas.banco",
tipo: "$$contas.tipo",
investimentos: {
$filter: {
input: "$$contas.investimentos",
as: "investimento",
cond: {
$eq: ["$$investimento.tipo", "fundo"]
}
}
}
}
}
}
}
}]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句