从两个数据库集合(Mongoose/MongoDB)中查询和匹配
Posted
技术标签:
【中文标题】从两个数据库集合(Mongoose/MongoDB)中查询和匹配【英文标题】:Query and Match from Two Database Collections (Mongoose/MongoDB) 【发布时间】:2021-09-27 23:06:09 【问题描述】:我需要帮助创建一个 mongoose 查询,该查询在用户集合中找到请求用户的喜欢,然后在帖子集合中搜索用户的喜欢。希望有人能告诉我我在查询中做错了什么,或者我怎样才能做得更好。
用户和帖子集合:
const users = [
_id: "1",
likes: ["1", "2"]
,
_id: "2",
likes: ["3"]
]
const posts = [
_id: "1",
stuff: "stuff1"
,
_id: "2",
stuff: "stuff2"
,
_id: "3",
stuff: "stuff3"
]
聚合查询:
router.post("/", authUser, async (req, res) =>
User.aggregate([
$match:
_id: ObjectId(req.user._id), //user 1
,
,
$unwind: "$likes",
,
$lookup:
from: "posts",
let: like: "$likes" ,
pipeline: [
$match:
$expr:
$eq: ["_id", "$$like"],
,
,
,
],
as: "matched_posts",
,
,
$unwind: "$matched_posts",
,
]).then((d) =>
console.log(d);
);
);
期望的输出:
const output = [
_id: "1",
stuff: "stuff1"
,
_id: "2",
stuff: "stuff2"
]
【问题讨论】:
【参考方案1】:$match
你的条件
$lookup
与帖子集合,传递 likes
作为 localField
和 _id
作为 foreignField
$unwind
解构likes
数组
$replaceRoot
替换 likes
对象
router.post("/", authUser, async (req, res) =>
User.aggregate([
$match: _id: ObjectId(req.user._id) ,
$lookup:
from: "posts",
localField: "likes",
foreignField: "_id",
as: "likes"
,
$unwind: "$likes" ,
$replaceRoot: newRoot: "$likes"
])
.then((d) =>
console.log(d);
);
);
Playground
【讨论】:
以上是关于从两个数据库集合(Mongoose/MongoDB)中查询和匹配的主要内容,如果未能解决你的问题,请参考以下文章
Mongoose/Mongodb 数据库调用以不一致的顺序返回数据
Mongoose/MongoDB 如果不存在则基于 Schema 创建集合
详解node+mongoose+mongoDb(mongoDb安装运行,在node中链接)