![](/img/trans.png)
[英]How can I build a mongoDB query to find any of myArray ids inside a document field?
[英]How can I sort array by a field inside a MongoDB document
我有稱為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
進行排序
我試圖在后端手動對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確實具有在服務器上執行此操作的“工具”,但在檢索數據時,在客戶端代碼中執行此操作最有意義,除非您實際上需要跨整個文檔“聚合”。
但是,現在都給出了兩個示例用法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.