gpt4 book ai didi

mongodb - Mongo按数组长度排序

转载 作者:IT老高 更新时间:2023-10-28 11:03:04 25 4
gpt4 key购买 nike

假设我有这样的 mongo 文档:

问题 1

{
answers:[
{content: 'answer1'},
{content: '2nd answer'}
]
}

问题 2

{
answers:[
{content: 'answer1'},
{content: '2nd answer'}
{content: 'The third answer'}
]
}

有没有办法按答案的大小对集合进行排序?

经过一些研究,我看到了添加另一个字段的建议,该字段将包含许多答案并将其用作引用,但可能有本地方法吗?

最佳答案

我认为您也许可以使用 $size,但这只是查找特定大小的数组,而不是排序。

来自 mongo 文档: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24size

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements. Indexes cannot be used for the $size portion of a query, although if other query expressions are included indexes may be used to search for matches on that portion of the query expression.

看起来您可以使用尚未推出的新聚合框架 edit: 轻松完成此操作。 http://www.mongodb.org/display/DOCS/Aggregation+Framework

更新现在聚合框架已经发布...

> db.test.aggregate([
{$unwind: "$answers"},
{$group: {_id:"$_id", answers: {$push:"$answers"}, size: {$sum:1}}},
{$sort:{size:1}}]);
{
"result" : [
{
"_id" : ObjectId("5053b4547d820880c3469365"),
"answers" : [
{
"content" : "answer1"
},
{
"content" : "2nd answer"
}
],
"size" : 2
},
{
"_id" : ObjectId("5053b46d7d820880c3469366"),
"answers" : [
{
"content" : "answer1"
},
{
"content" : "2nd answer"
},
{
"content" : "The third answer"
}
],
"size" : 3
}
],
"ok" : 1
}

关于mongodb - Mongo按数组长度排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9040161/

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