gpt4 book ai didi

javascript - MongoDB - 当尝试根据查询字符串查找文档时,如何将 .or 转换为等效聚合?

转载 作者:行者123 更新时间:2023-12-03 02:55:01 25 4
gpt4 key购买 nike

工作响应示例(标签文档):

[ 
{
_id: 5a27a6b09fe2c0057782199a,
label: '05',
createdBy: 5a27a66f4db90e0541315114,
createdAt: 2017-12-06T08:17:09.480Z,
updatedAt: null,
__v: 0,
occurrences: 1
},
...
]

这是我的原始代码:

Tag.find({})
.or({label: new RegExp(config.query, 'i')})
.sort(config.sortBy)
.limit(config.limit)
.skip(config.offset)
.exec((err, tags) => {});

这非常有效,但是我遇到了一种情况,这种方法不起作用(与问题无关)。

这个重写的代码还将包含 Page 文档,特别是 tags 数组。以下是 Page 文档示例:

{
"_id" : ObjectId("5a27a6b09fe2c00577821999"),
"organisation" : ObjectId("5a17eb11bf3f990b94c01735"),
"createdBy" : ObjectId("5a27a66f4db90e0541315114"),
"createdAt" : ISODate("2017-12-06T08:13:36.199Z"),
"updatedBy" : ObjectId("5a27a66f4db90e0541315114"),
"updatedAt" : ISODate("2017-12-06T08:18:20.809Z"),
"tags" : [
ObjectId("5a27a6b09fe2c0057782199a"),
ObjectId("5a27a7859fe2c005778219a6"),
ObjectId("5a27a7859fe2c005778219a4")
],
"content" : "asd",
"description" : "asdasd",
"title" : "testing tag creation",
"parent" : null,
"__v" : 0
}

这就是我现在所拥有的:

Page.aggregate([
{
$unwind: "$tags"
},

// This bit ain't working
{
$match: {
$or: [{
label: new RegExp(config.query, 'i')
}]
}
},

{
$group: {
_id: "$tags",
occurrences: {
$sum: 1
}
}
},
{
$lookup: {
from: "tags",
localField: "_id",
foreignField: "_id",
as: "tagsData"
}
},
{$limit: config.limit},
{$skip: config.offset},
{$sort: {[config.sortBy]: config.order}},
{
$project: {
occurrences: "$occurrences",
tagData: {
$arrayElemAt: [
"$tagsData", 0
]
}
}
},
{
$addFields: {
"tagData._id": "$_id",
"tagData.occurrences": "$occurrences"
}
},
{
$replaceRoot: {
newRoot: "$tagData"
}
}
], (err, tags) => {
console.log(tags);
});

我想做的是替换这个位:

.or({label: new RegExp(config.query, 'i')})

与聚合框架中的等效项。

我上面的尝试总是产生一个空数组,即使我这样做 $match: {label: '05'} 例如,我没有得到任何结果。

我一直在检查文档,但它们对我来说并不是那么明显,因为这是我第一次使用聚合。

我看过这两个:

https://docs.mongodb.com/manual/reference/operator/aggregation/match/ https://docs.mongodb.com/manual/reference/operator/aggregation/or/

所以我的问题是我的查询位做错了什么?

最佳答案

正如我在评论中提到的 Tag.find({}).or({label: new RegExp(config.query, 'i')}) 对我来说毫无意义,对大多数人来说也没有意义聚合管道。

我将在答案中针对管道中的一些明显问题:

  • Page 仅具有标签的 Id,因此标签标签的 $match 应在标签可用的 $lookup 阶段之后完成。
  • 自 v3.3 起,无需在 $lookup 之前进行 $unwind
  • $lookup本身引用了错误的字段localField: "_id"是页面的_id,它很难与标签集合中的任何文档匹配
  • 尚不清楚 $group 是否应该计算标签或页面。我在下面的答案中假设是前者。
  • 所有转换阶段 - 很难猜测其意图,因此我将它们从下面的代码片段中排除。为了简洁起见,还删除了排序限制阶段。

用于计算所有页面上使用与正则表达式 /05/i 匹配的标签的次数的 shell 查询:

db.pages.aggregate([
{
$lookup: {
from: "tags",
localField: "tags",
foreignField: "_id",
as: "tagsData"
}
},
{
$unwind: "$tagsData"
},
{
$match: {
"tagsData.label": /05/i
}
},
{
$group: {
_id: "$tagsData",
occurrences: {
$sum: 1
}
}
}
]);

关于javascript - MongoDB - 当尝试根据查询字符串查找文档时,如何将 .or 转换为等效聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47672413/

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