mongodb - MongoDB多对多查找
问题描述
我有以下情况。
Offer {
id,
name
}
OfferCategory {
offerId,
categoryId
}
Category {
id,
name
}
我想检索 al Offers 及其类别,包括同一查询中的名称(在此之前,我使用 geoNear 步骤进行过滤)。我有这个,但它带来了一个空categoriesObj
数组。我认为localField
最后一个$lookup
操作不正确:
db.Offer.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ -58, -34 ] },
distanceField: "dist.calculated",
maxDistance: 200,
spherical: true
}
},
{
$lookup: {
from: "OfferCategory",
localField: "_id",
foreignField: "offerId",
as: "categories"
}
},
{
$lookup: {
from: "Category",
localField: "categories._id",
foreignField: "_id",
as: "categoriesObjs"
}
},
]);
解决方案
您可以将此聚合与 mongoDB 版本 ^3.6 一起使用
db.offers.aggregate([
{ $geoNear: {
near: { type: "Point", coordinates: [ -58, -34 ] },
distanceField: "dist.calculated",
maxDistance: 200,
spherical: true
}},
{ $lookup: {
from: "offerCategory",
let: { offerId: "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$$offerId", "$offerId"] } } },
{ $lookup: {
from: "Category",
let: { categoryId: "$categoryId" },
pipeline: [{ $match: { $expr: { $eq: ["$$categoryId", "$id"] } } }],
as: "cateogries"
}}
],
as: "offerCategories"
}
}
]);
推荐阅读
- image - 有没有办法在加载屏幕期间缓存所有网络图像?扑
- jquery - 使用 jquery 突出显示文本
- firebase - 将选取的图像上传到 Firestore 存储
- mobile-safari - iOS 15 Safari CSS
- c# - 平行装配线平衡问题的模拟退火
- mongodb - MongoDB E11000 dup key on insertMany 但不在 insertOne 上的空集合上,默认索引
- javascript - Flask 应用程序运行两次
- python - 写入文件时如何在新行中输入文本?
- sql - PL/pgSQL 重启生成序列
- android - 如何修复 Android Room (Kotlin) 中的 TypeConverter 类