Answer the question
In order to leave comments, you need to log in
How to select specific sub-documents by criteria?
Having such a scheme of articles with subdocuments of comments, you need to select only certain authors
article: {
text: {type: String, require: true},
comments: [{
text: {type: String, required: true},
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
}
}],
created_at: { type: Date, "default": Date.now}
},
db.getCollection('article').findOne({
'_id': ObjectId("564680c59bfd4a0a49745282"),
'comments.user_id': {$in : [ObjectId("563e3337e2bf6c431b297d41"), ObjectId("563e3337e2bf6c431b297d42")]}
})
db.getCollection('article').find(
{'_id': ObjectId("564680c59bfd4a0a49745282")},
{ comments : { $elemMatch: { user_id : {$in : [ObjectId("563e3337e2bf6c431b297d41"),ObjectId("563e3337e2bf6c431b297d42") ]}} } }
)
Answer the question
In order to leave comments, you need to log in
if I don't confuse anything, in the second request you need to specify "storage" ('comments') as a key, and not what we are looking for, but in $elemMatch we are already talking about what, only just 'user_id'
The find command is designed to find the documents themselves, not their contents (although there are partial get functions). Therefore, you can receive documents completely and filter them already on the "client", if you filter a lot, then it makes sense to select comments in a separate collection.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question