gpt4 book ai didi

javascript - 如何按 MongoDB 文档中的字段对数组进行排序

转载 作者:可可西里 更新时间:2023-11-01 10:03:36 24 4
gpt4 key购买 nike

我有一个名为question的文档

var QuestionSchema = new Schema({
title: {
type: String,
default: '',
trim: true
},
body: {
type: String,
default: '',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
category: [],
comments: [{
body: {
type: String,
default: ''
},
root: {
type: String,
default: ''
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
createdAt: {
type: Date,
default: Date.now
}
}],
tags: {
type: [],
get: getTags,
set: setTags
},
image: {
cdnUri: String,
files: []
},
createdAt: {
type: Date,
default: Date.now
}
});

因此,我需要按根字段对 comments 进行排序,如下所示 example

我尝试在后端手动对 comments 数组进行排序,并尝试使用聚合,但无法对其进行排序。请帮忙。

最佳答案

假设 Question 是您代码中的模型对象,并且您当然希望从 createdAt 开始按“日期”对您的“评论”进行排序,然后使用 。 aggregate() 你会用这个:

Question.aggregate([
// Ideally match the document you want
{ "$match": { "_id": docId } },

// Unwind the array contents
{ "$unwind": "comments" },

// Then sort on the array contents per document
{ "$sort": { "_id": 1, "comments.createdAt": 1 } },

// Then group back the structure
{ "$group": {
"_id": "$_id",
"title": { "$first": "$title" },
"body": { "$first": "$body" },
"user": { "$first": "$user" },
"comments": { "$push": "$comments" },
"tags": { "$first": "$tags" },
"image": { "$first": "$image" },
"createdAt": { "$first": "$createdAt" }
}}
],
function(err,results) {
// do something with sorted results
});

但这确实有点矫枉过正,因为您没有在文档之间“聚合”。只需使用 JavaScript 方法即可。如.sort() :

Quesion.findOneById(docId,function(err,doc) {
if (err) throw (err);
var mydoc = doc.toObject();
mydoc.questions = mydoc.questions.sort(function(a,b) {
return a.createdAt > b.createdAt;
});
console.log( JSON.stringify( doc, undefined, 2 ) ); // Intented nicely
});

因此,虽然 MongoDB 确实具有在服务器上执行此操作的“工具”,但在您检索数据时在客户端代码中执行此操作最有意义,除非您实际上需要跨文档“聚合”。

但是现在已经给出了两个示例用法。

关于javascript - 如何按 MongoDB 文档中的字段对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31048478/

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