gpt4 book ai didi

mongodb - 按数组长度排序

转载 作者:可可西里 更新时间:2023-11-01 09:06:51 25 4
gpt4 key购买 nike

如何根据数组字段的元素数量对查询进行排序?

假设我有这样的记录

{
title: '',
author: '',
votes: [id,id,id]
}

我想按投票数组的长度排序

最佳答案

$size 的帮助下使用聚合框架MongoDB 2.6 及更高版本的运算符:

db.collection.aggregate([
// Project with an array length
{ "$project": {
"title": 1,
"author": 1,
"votes": 1,
"length": { "$size": "$votes" }
}},

// Sort on the "length"
{ "$sort": { "length": -1 } },

// Project if you really want
{ "$project": {
"title": 1,
"author": 1,
"votes": 1,
}}
])

足够简单。

如果您没有可用的 2.6 版,您仍然可以做更多的工作:

db.collection.aggregate([
// unwind the array
{ "$unwind": "$votes" },

// Group back
{ "$group": {
"_id": "$id",
"title": { "$first": "$title" },
"author": { "$first": "$author" },
"votes": { "$push": "$votes" },
"length": { "$sum": 1 }
}},

// Sort again
{ "$sort": { "length": -1 } },

// Project if you want to
{ "$project": {
"title": 1,
"author": 1,
"votes": 1,
}}
])

差不多就是这样。

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

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