【发布时间】:2014-07-04 16:59:04
【问题描述】:
我了解您可以使用 $elemMatch 作为投影来限制子集合数组中的项目。当这样使用它时,无论是否还指定了query projections,它都会返回匹配的子文档的所有字段。
是否可以限制匹配子文档中返回的字段?你会怎么做?
使用版本 3.8.9。
鉴于简单的模式:
var CommentSchema = mongoose.Schema({
body: String,
created: {
by: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
}
});
var BlogSchema = mongoose.Schema({
title: String,
blog: String,
created: {
by: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
},
comments: [CommentSchema]
});
var Blog = mongoose.model('Blog',modelSchema);
示例
Blog.findOne({_id: id}, {_id: 1, comments: {$elemMatch: {'created.by': 'Jane'}, body: 1}}, function(err, blog) {
console.log(blog.toJSON());
});
// outputs:
{
_id: 532cb63e25e4ad524ba17102,
comments: [
_id: 53757456d9c99f00009cdb5b,
body: 'My awesome comment',
created: { by: 'Jane', date: Fri Mar 21 2014 20:34:45 GMT-0400 (EDT) }
]
}
// DESIRED OUTPUT
{
_id: 532cb63e25e4ad524ba17102,
comments: [
body: 'My awesome comment'
]
}
【问题讨论】:
标签: javascript node.js mongodb mongoose aggregation-framework