[英]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.