How to query only some fields from a mongodb sub-document?

943 views Asked by At

For my test application, I store articles and comments using this schema:

var commentSchema = new mongoose.Schema({
  author: String,
  text: String,
  created: Date
});

var articleSchema = new mongoose.Schema({
  title: String,
  text: String,
  comments: [commentSchema]
});

Now, I’m trying to get all the comments (which are only stored as sub-documents in the articles) posted after a certain date. Additionally, I only want the text field, not the author one. This would be equivalent to: Comment.find({created: {$gte: date}}, "text") but since comments are not stored in their own data store, this would not work.

1

There are 1 answers

0
user602525 On
db.articles.find({'comments.created': {$gte: date}}, {_id: 0, 'comment.text': 1})

I haven't used mongoose, so this solution assumes that the subdocuments are the full documents and not just an array of _ids