mongodb通过嵌入式数组进行搜索



我有一个Mongodb文档结构,有很多类似的文档。

{   '_id': ObjectID(62f8199dc1e8c0f11820cb91)
'name': 'foo',
'score': 4500,
'searchable': [
{
'title': 'blah',
'date': 'some_date',
'search_text': "Blah blah blah ...."
},
{
'title': 'bleep',
'date': 'some_date',
'search_text': "Lorem Lorem Lorem ...."
},
{
'title': 'bloop',
'date': 'some_date',
'search_text': "Ipsum Ipsum Ipsum ...."
}]
},

我一直在尝试在任何'searchable'数组对象'search_text'字段中搜索特定字符串,但已被'score'(最小值和最大值(过滤。我需要返回字符串所在的'searchable'中的哪个对象,以及该对象属于哪个文档…

我认为这是一项用于聚合和$unwind的工作,但未能产生可行的结果。非常感谢您的帮助。

使用上面的示例文档,如果我搜索

"Lorem的"分数"在3000和5000之间;

我想知道它出现在documentID: '62f8199dc1e8c0f11820cb91', 'searchable': {1}'

如果文档中有多个"可搜索"匹配,则也返回它们,如:documentID: '62f8199dc1e8c0f11820cb91', 'searchable': {1, 2, 5,}

这不是最性感的管道,但这里有一个例子:

(如果我们可以返回实际匹配而不是元素的匹配索引,语法可能会更干净(

const input = {
text: "Lorem",
minScore: 3000,
maxScore: 5000
};
db.collection.aggregate([
{
$match: {
"searchable.search_text": {
$regex: input.text
},
score: {
$gte: input.minScore,
$lte: input.maxScore
}
}
},
{
$project: {
documentID: "$_id",
_id: 0,
searchable: {
$map: {
input: {
$filter: {
input: {
"$map": {
"input": {
$zip: {
inputs: [
"$searchable",
{
"$range": [
0,
{
$size: "$searchable"
}
]
}
]
}
},
in: {
"$mergeObjects": [
{
"$arrayElemAt": [
"$$this",
0
]
},
{
index: {
"$arrayElemAt": [
"$$this",
1
]
}
}
]
}
}
},
cond: {
"$regexMatch": {
"input": "$$this.search_text",
"regex": input.text
}
}
}
},
in: "$$this.index"
}
}
}
}
])

Mongo游乐场

最新更新