我正在尝试在聚合中进行查找,但是在尝试获取与数组中的元素匹配的所有文档时遇到了问题。目标是获得“ $ services”和“ $$ services”之间交点的所有雇员。这两个是ObjectID的数组。查找将在员工集合中进行。这是我尝试过的方法,但之后不知道如何匹配:
{
$lookup: {
from: collection_names.EMPLOYEE,
let: { services: "$services._id" },
pipeline: [
{
$project: {
_id: 0,
intersection: { $setIntersection: ["$services", "$$services"] },
}
},
// {
// $match: { }
// }
],
as: "employees"
}
},
这是完整的汇总:
collection.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: correct_format_loc, },
key: 'location',
distanceField: 'location.dist',
maxDistance: range * 1000, // 1000 meters
query: { name: re },
spherical: true,
}
},
{
$lookup: {
from: collection_names.SERVICE,
let: { business: "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$business", "$$business"] } } },
{
$project: {
_id: 1,
name: 1,
price: 1,
category: 1,
duration: 1,
}
}
],
as: "services"
}
},
{
$lookup: {
from: collection_names.EMPLOYEE,
let: { services: "$services._id" },
pipeline: [
{
$project: {
_id: 0,
intersection: { $setIntersection: ["$services", "$$services"] },
}
},
// {
// $match: { }
// }
],
as: "employees"
}
},
{
$project: {
name: "$name",
address: "$address",
location: "$location",
contact: "$contact",
description: "$description",
image_paths: "$image_paths",
services: '$services',
employees: '$employees',
rating_avg: {
$avg: "$services.rating"
}
}
},
]).toArray()
答案 0 :(得分:0)
我发现解决方案在两个投影之间有一个匹配项。这些更改是在我写的问题的最后一个$lookup
中完成的。
我所做的是获取相交并将其投影为新属性,然后与表达式匹配,然后删除不需要的不必要属性。更改后的外观如下:
{
$lookup: {
from: collection_names.EMPLOYEE,
let: { services: '$services._id' },
pipeline: [
{
$project: {
name: 1,
description: 1,
rating: 1,
image_path: 1,
services: 1,
service_ids: { $setIntersection: ['$services', '$$services'] }
}
},
{ $match: { $expr: { $eq: ['$services', '$service_ids'] } } },
{
$project: {
service_ids: 0,
services: 0,
}
}
],
as: "employees"
}
},