我是 MongoDB 的新手,我想知道如何根据对象数组中的“计算值”查找文档。
例如,假设计算文本是“transcript .data”下所有文本的串联。
如果用户搜索“hello”,我想返回两个文档,如果用户搜索“hello world”,我想返回第一个文档。
[{
"_id": ...
"transcript": {
"data": [
{
"text": "hello "
},
{
"text": "world"
}
],
}
},{
"_id": ...
"transcript": {
"data": [{
text: "hello"
}],
}
}]
我在 node.js 环境中使用 MongoDB 3.6.3。所以我不能将 $expr
与 $function
一起使用。此外,$where
操作对我也不起作用,正如 in this question 所指出的那样。
如果有人能提供帮助,我将不胜感激!
答案 0 :(得分:1)
我相信您可以通过这样的聚合管道实现您的目标:
var input = "hello world".split(' ');
db.collection.aggregate(
[
{
$match: {
$expr: {
$setIsSubset: [
input,
{
$map: {
input: "$transcript.data",
as: "t",
in: { $trim: { input: "$$t.text" } }
}
}
]
}
}
}
])
但是您必须将输入短语作为字符串数组提供给 mongodb。