A
A
Alexander2015-11-16 00:33:45
MongoDB
Alexander, 2015-11-16 00:33:45

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}
    },

Wrote this query
db.getCollection('article').findOne({
        '_id': ObjectId("564680c59bfd4a0a49745282"),
        'comments.user_id': {$in : [ObjectId("563e3337e2bf6c431b297d41"), ObjectId("563e3337e2bf6c431b297d42")]}
        })

I expected to see comments only from these authors, but I see from everyone. Apparently, according to 1 condition with Id, mongo pulls out all the data for this article, I went further, wrote such a request
db.getCollection('article').find(
        {'_id': ObjectId("564680c59bfd4a0a49745282")},
        { comments : { $elemMatch: { user_id : {$in : [ObjectId("563e3337e2bf6c431b297d41"),ObjectId("563e3337e2bf6c431b297d42") ]}} } } 
        )

but also everything is not correct, it returns only 1 record,
please tell me how to solve this seemingly simple task.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arman, 2015-11-16
@Arik

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'

L
lega, 2015-11-16
@lega

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 question

Ask a Question

731 491 924 answers to any question