gpt4 book ai didi

mongodb - 带有构面计数的 Mongo 搜索结果

转载 作者:行者123 更新时间:2023-12-03 02:20:04 24 4
gpt4 key购买 nike

我是 Mongo 新手,我希望使用 mgo 驱动程序在 Go 中实现分面搜索。我需要获取与我的查询匹配的文档以及方面计数。

我当前的实现是执行一个查询来获取文档,然后使用相同的参数进行另一个查询来获取构面计数,但这似乎效率很低。有没有好的方法可以一步完成此操作?

例如,如果我有一系列书籍:

[{
title: "Book One",
author: "Author A",
numPages: 20,
type: "book"
},
{
title: "Book Two",
author: "Author B",
numPages: 40,
type: "book"
},
...
...
...
{
title: "Magazine AA",
author: "Author A",
numPages: 10,
type: "magazine"
}]

首先,我获取与我的查询匹配的文档:

err = books.Find(bson.M{"$and": matches}).All(&results)

然后我使用聚合管道和 $facet 重复查询以获取构面计数:

err = Pipe([]bson.M{
{"$match": bson.M{"$and": matches}},
{"$facet": bson.M{
"type": []bson.M{bson.M{"$sortByCount": "$type"}},
"author": []bson.M{bson.M{"$sortByCount": "$author"},
}},
}).All(&facets)

我还见过 $out,它可以让我将结果写入临时集合,然后我可以用它来确定构面计数,但我不知道这是否更有效。

最佳答案

Is there a good way to do this in a single step?

是的,您可以使用分面搜索来添加非分面结果。例如:

pipeline := []bson.M{ 
{"$match": bson.M{"type": bson.M{"$in": []string{"book", "magazine"}}}},
{"$facet": bson.M{"type": []bson.M{{"$sortByCount":"$type"}},
"author": []bson.M{{"$sortByCount":"$author"}},
"unfaceted": []bson.M{{"$match": bson.M{} }},
},
},
}
err = collection.Pipe(pipeline).All(&resp)

上面的unfaceted $match没有条件(空),因为第一个$match阶段已经过滤到所需的子集的文件。

这将为您提供以下结果:

{
"type": [
{
"_id": "book",
"count": 2
},
{
"_id": "magazine",
"count": 1
}
],
"author": [
{
"_id": "Author A",
"count": 2
},
{
"_id": "Author B",
"count": 1
}
],
"unfaceted": [
{
"_id": ObjectId(".."),
"title": "Magazine AA",
"author": "Author A",
"numPages": 10,
"type": "magazine"
},
{
"_id": ObjectId(".."),
"title": "Book Two",
"author": "Author B",
"numPages": 40,
"type": "book"
},
{
"_id": ObjectId(".."),
"title": "Book One",
"author": "Author A",
"numPages": 20,
"type": "book"
}
]
}

现在您可以迭代 unfaceted 部分,而不是发送单独的查询。另请参阅$facet有关运算符的更多示例和说明。

关于mongodb - 带有构面计数的 Mongo 搜索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43346011/

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