使用带有$lookup和$match的聚合搜索查询mongodb
我正在为一个我不知道有多真实的问题而挣扎。。。我假装做一个搜索输入,在那里我想找到一个客户,并从这个客户那里获得我需要的所有信息。 我有三个收藏 客户集合 费率收集 配置集合 我正在执行的查询是。。。(我只从我的应用程序中收到searchTerm) 但是这个查询不起作用,它说$rate没有定义。。。我想我不知道它到底是怎么工作的,我怎么能申报美元汇率呢?我认为如果cliente.rate是clientModel的一个属性,那么它的定义是。。。请帮助您可以尝试以下操作:使用带有$lookup和$match的聚合搜索查询mongodb,mongodb,Mongodb,我正在为一个我不知道有多真实的问题而挣扎。。。我假装做一个搜索输入,在那里我想找到一个客户,并从这个客户那里获得我需要的所有信息。 我有三个收藏 客户集合 费率收集 配置集合 我正在执行的查询是。。。(我只从我的应用程序中收到searchTerm) 但是这个查询不起作用,它说$rate没有定义。。。我想我不知道它到底是怎么工作的,我怎么能申报美元汇率呢?我认为如果cliente.rate是clientModel的一个属性,那么它的定义是。。。请帮助您可以尝试以下操作: db.clienteMod
db.clienteModel.aggregate([
{
$match: {
$or: [
{ name: { '$regex': req.body.searchTerm, '$options': 'i' } },
]
}
},
{
$lookup: {
from: "rate",
let: { "rateId": "$rate" },
pipeline: [
{
$match: {
$expr: { $eq: ["$_id", "$$rateId"] },
}
}
],
as: "rateDetails"
}
},
{
$lookup: {
from: "config",
let: { "rateId": "$rate" },
pipeline: [
{
$match: {
$expr: { $eq: ["$idRate", "$$rateId"] },
}
}
],
as: "configDetails"
}
},
]);
输出:
{
"_id" : ObjectId("5e7fb25ddc976375d3c224eb"),
"name" : "Jhon",
"rate" : ObjectId("5e7fb22fdc976375d3c224ea"),
"rateDetails" : [
{
"_id" : ObjectId("5e7fb22fdc976375d3c224ea"),
"title" : "Rate for sellers",
"margin" : 10
}
],
"configDetails" : [
{
"_id" : ObjectId("5e7fb2a2dc976375d3c224ec"),
"idRate" : ObjectId("5e7fb22fdc976375d3c224ea"),
"maring" : 8
}
]
}
非常感谢,你成功了!我必须学习更多关于聚合的知识,我想我缺少了一些概念。。。就像“让”来定义。。。再次感谢!
{
_id: '5e7276249110c43528f21402'
idRate: '5e790595b0d727313cb56d3b'
maring: 8,
}
clienteModel.aggregate([
//in the first stage i find the client by searchTerm that contains the Name;
{
$match: {
$or: [
{ name: { '$regex': req.body.searchTerm, '$options': 'i' } },
]
}
},
//in the second stage i would like to receive only the Rate that match with the client.rate
{
$lookup: {
from: "rates",
as: "rate",
pipeline: [
{
$match: {
_id: $rate
}
}
]
}
}
//in the third stage, i would like to bring the configs that match with client.rate
{
$lookup: {
from: "configs",
as: "config",
pipeline: [
{
$match: {
idRate: $rate
}
}
]
}
}
])
db.clienteModel.aggregate([
{
$match: {
$or: [
{ name: { '$regex': req.body.searchTerm, '$options': 'i' } },
]
}
},
{
$lookup: {
from: "rate",
let: { "rateId": "$rate" },
pipeline: [
{
$match: {
$expr: { $eq: ["$_id", "$$rateId"] },
}
}
],
as: "rateDetails"
}
},
{
$lookup: {
from: "config",
let: { "rateId": "$rate" },
pipeline: [
{
$match: {
$expr: { $eq: ["$idRate", "$$rateId"] },
}
}
],
as: "configDetails"
}
},
]);
{
"_id" : ObjectId("5e7fb25ddc976375d3c224eb"),
"name" : "Jhon",
"rate" : ObjectId("5e7fb22fdc976375d3c224ea"),
"rateDetails" : [
{
"_id" : ObjectId("5e7fb22fdc976375d3c224ea"),
"title" : "Rate for sellers",
"margin" : 10
}
],
"configDetails" : [
{
"_id" : ObjectId("5e7fb2a2dc976375d3c224ec"),
"idRate" : ObjectId("5e7fb22fdc976375d3c224ea"),
"maring" : 8
}
]
}