gpt4 book ai didi

mongodb - 过滤集合但按内部属性排序

转载 作者:数据小太阳 更新时间:2023-10-29 03:26:33 24 4
gpt4 key购买 nike

考虑到我有如下的文档集合,我想获取如下返回的信息:

campaignID = 12 的事件中选择所有条目,按 entries.questionscorrect 降序排序,限制为 10。

我已经对一些查询进行了尝试,但我似乎陷入了这样一个事实,即我在一个级别上进行选择,但想在较低级别(即属性)上订购。

这是我目前所拥有的:

db.getCollection('main').find({"id":4}, {"entries": 1}).sort({"questionscorrect": -1}).limit(2)

请问我如何用 Go (Mgo) 语法或直接的 MongoDB 查询来编写它?

我不断收到返回的信息,但按数量排序

{
"_id": ObjectId("57f4a590a4be269aa54a0505"),
"campaignID": 12,
"name": "name-here",
"description": "description-here",
"entries": [{
"id": 1,
"nickname": "conorh",
"name": "conor h***",
"email": "ch@gmail.com",
"agreeTerms": true,
"optInMarketing": false,
"questionscnswered": 10,
"questionscorrect": 3
}, {
"id": 2,
"nickname": "bobs",
"name": "bob smyth",
"email": "bs12121@gmail.com",
"agreeTerms": true,
"optInMarketing": false,
"questionscnswered": 10,
"questionscorrect": 6
}, {
"id": 3,
"nickname": "jd12",
"name": "jane doe",
"email": "janedough@gmail.com",
"agreeTerms": true,
"optInMarketing": false,
"questionscnswered": 10,
"questionscorrect": 1
}]
}

最佳答案

尝试以下:

db.getCollection('main').aggregate([
{$match: {"campaignID" : 12.0}},
{$unwind:"$entries"},
{$sort: {"entries.questionscorrect": -1}},
{$group:{_id:"$_id",
"entries":{$push:"$entries"}}}
])

关于mongodb - 过滤集合但按内部属性排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39867585/

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