gpt4 book ai didi

mongodb - 只从 mongodb 返回数组中的命中

转载 作者:行者123 更新时间:2023-12-03 15:59:32 24 4
gpt4 key购买 nike

所以我有一个包含一些嵌套文档的 mongodb 集合。示例文档如下所示:

{
"_id": "5afa9472e937b7254a306ff6",
"import_date": "2018-05-15T08:04:02.813Z",
"some_more_things": "foo",
"meta": {
"participants": [{ "name": "Ben" }, { "name": "Mary" }],
"messages": [
{
"tokens": [
{ "token": "What" },
{ "token": "do" },
{ "token": "you" },
{ "token": "do" },
{ "token": "today" }
],
"time": "2018-05-09T08:38:19.000Z"
},
{
"tokens": [
{ "token": "Just" },
{ "token": "lying" },
{ "token": "around" }
],
"time": "2018-05-09T08:40:08.000Z"
},
{
"tokens": [
{ "token": "What" },
{ "token": "about" },
{ "token": "you" }
],
"time": "2018-05-09T08:40:11.000Z"
}
]
}
}

我现在正在寻找一种有效的方法来搜索包含特定 token 的消息。我使用以下查询来执行此操作:

db.conversations.find({'meta.messages.tokens.token': /^What$/i})
.projection({'import_date': 1, 'meta.messages': 1})
.sort({_id:-1})
.limit(100)

这样我就可以找到我想要的文档,同时获得完整的 messages 数组。有没有一种方法可以让我只获取与我的正则表达式匹配的 messages 数组的项目?结果应该如下所示(因此只有我的示例文档的第一项和最后一项)。

{
"_id": "5afa9472e937b7254a306ff6",
"import_date": "2018-05-15T08:04:02.813Z",
"meta": {
"participants": [{ "name": "Ben" }, { "name": "Mary" }],
"messages": [
{
"tokens": [
{ "token": "What" },
{ "token": "do" },
{ "token": "you" },
{ "token": "do" },
{ "token": "today" }
],
"time": "2018-05-09T08:38:19.000Z"
},
{
"tokens": [
{ "token": "What" },
{ "token": "about" },
{ "token": "you" }
],
"time": "2018-05-09T08:40:11.000Z"
}
]
}
}

最佳答案

您可以使用$indexOfBytes检查每个字符串中是否存在 What。您还需要$map$filter$anyElementTrue为嵌套数组构建过滤条件:

db.collection.aggregate([
{
$addFields: {
"meta.messages": {
$filter: {
input: "$meta.messages",
as: "m",
cond: {
$anyElementTrue: {
$map: {
input: "$$m.tokens",
in: { $gte: [ { $indexOfBytes: [ "$$this.token", "What" ] }, 0 ] }
}
}
}
}
}
}
}
])

Mongo Playground

如果您需要正则表达式,您可以查看$regexMatch4.2 中引入,并将其用作 $indexOfBytes

的替代品

关于mongodb - 只从 mongodb 返回数组中的命中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58310161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com