我想弄清楚如何同时正确搜索集合和关系?
假设我有
Users
这样的设置:
{
_id: ObjectId("1234"),
firstName: "John",
lastName: "Smith"
}
和
Posts
设置如下:
{
_id: ObjectId("8877"),
user: ObjectId("1234")
title: "My Post",
}
如何对帖子进行搜索,以获取与我在
post.title
或 user.firstName
或 user.lastName
上的查询相匹配的任何帖子?
我尝试过使用
$lookup
进行聚合,并且已经接近了。这缩小了嵌套关系的范围,但我不确定如何检查当前集合。
[
{
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user',
pipeline: [
{
$search: {
compound: {
should: [
{
search: {
query: "Jim",
path: 'user.firstName',
},
},
],
},
},
},
],
},
},
{ $unwind: '$user' },
]
如果查找管道
$search
按照您想要的方式工作,则在unwind
ing之后,下一步将检查"user"
字段存在OR标题是否与查询匹配。放松时记得使用preserveNullAndEmptyArrays
。
db.posts.aggregate([
{
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "user",
pipeline: [
{
$search: {
compound: {
should: [
{
search: {
query: "Jim",
path: "user.firstName"
}
}
]
}
}
}
]
}
},
{
$unwind: {
path: "$user",
// preserve is required for OR-matching next
preserveNullAndEmptyArrays: true
}
},
{
$match: {
$or: [
{ "user": { $ne: null } },
// replace "john" with your search term
{ "title": "john" }
]
}
}
])
$search
- 游乐场本身没有 $search 功能。
如果您只想小写名称匹配而不是
$search
:
db.posts.aggregate([
{
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "user",
pipeline: [
{
$match: {
$expr: {
$or: [
{ $eq: [{ $toLower: "$firstName" }, "john"] },
{ $eq: [{ $toLower: "$lastName" }, "john" ] }
]
}
}
}
]
}
},
{
$unwind: {
path: "$user",
// preserve is required for OR-matching next
preserveNullAndEmptyArrays: true
}
},
{
$match: {
$or: [
{ "user": { $ne: null } },
// replace "john" with your search term
{ "title": "john" }
]
}
}
])
A working Mongo Playground 使用小写名称匹配
与上述交替,放松后完成所有匹配的游乐场。