[英]How to join then perform query on mongoose
假设我有 2 个架构
// User
{
name: { type: Types.Name, required: true, index: true }
}
// Book
{
name: { type: Types.String, index: true },
author: { type: Types.Relationship, ref: 'User', index: true }
}
我想在“name”字段和“author.name”字段之间使用 OR 运算符对 Book 模式执行搜索查询(这意味着如果我输入“abc”搜索,它将返回名称包含“abc”或 Books 的任何书籍'作者姓名包括“abc”)。 我怎样才能做到这一点? 感谢您的帮助,在此先感谢。
P/S: 如果我有
User Collection
_id name
1 Foo
2 Bar
3 XYZ
Book Collection
_id name author
1 BookA 1
2 Foo 2
3 BookC 2
4 BookD 3
因此,当我在 Book Collection 中输入“Foo”搜索键进行查询时,它将返回:
_id name author
1 BookA 1 (because author 1 name "Foo")
2 Foo 2
以下查询会有所帮助:
db.Book.aggregate([
{
$lookup: {
from: "User",
localField: "author",
foreignField: "_id",
as: "user"
}
},
{
$unwind: {
path: "$user",
preserveNullAndEmptyArrays: true
}
},
{
$match: {
$expr: {
$or: [
{
$eq: [
"$name",
"Foo" // Replace with your search string.
]
},
{
$eq: [
"$user.name",
"Foo" // Replace with your search string.
]
}
]
}
}
},
{
$project: {
name: 1,
author: 1
}
}
])
注意:以上查询是在纯 Mongo 中,您可以轻松地将其转换为您需要的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.