简体   繁体   English

我如何按MongoDB文档中的字段对数组排序

[英]How can I sort array by a field inside a MongoDB document

I have document called question 我有称为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
    }
});

As a result, I need to sort comments by root field, like this 结果,我需要像这样按根字段对comments进行排序 例

I tried to sort the array of comments manually at backend and tried to use aggregation, but I was not able to sort this. 我试图在后端手动对comments数组进行排序,并尝试使用聚合,但无法对此进行排序。 Help please. 请帮助。

Presuming that Question is a model object in your code and that of course you want to sort your "comments by "date" from createdAt then using .aggregate() you would use this: 假定该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
});

But that is really overkill since you are not "aggregating" between documents. 但这实在是太过分了,因为您不是在文档之间“聚合”。 Just use the JavaScript methods instead. 只需使用JavaScript方法即可。 Such as .sort() : .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
});

So whilst MongoDB does have the "tools" to do this on the server, it makes the most sense to do this in client code when you retrieve the data unless you actually need to "aggregate" accross documents. 因此,尽管MongoDB确实具有在服务器上执行此操作的“工具”,但在检索数据时,在客户端代码中执行此操作最有意义,除非您实际上需要跨整个文档“聚合”。

But both example usages have been given now. 但是,现在都给出了两个示例用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM