Tobias
Tobias

Reputation: 903

Counting entries of subdocument in MongoDB documents

I have a document structure like so

{
    "_id" : "3:/content/somepath/test.txt",
    "_revisions" : {
        "r152f47f1daf-0-2" : "c",
        "r152f48413c1-0-2" : "c",
        "r152f4851bf7-0-1" : "c"
    }
}

My task is to find all documents with the following conditions:

The first part is easy, I have solved it with

db.nodes.find( {'_id': /^5:/} )

But I am struggling with the second part, am supposed to use $gt.

Since I am new to MongoDB, I was first looking at $size, but _revisions is not an array, it is a subdocument, right?.

Was also looking at $unwind and then counting the results, but that does not make sense either, since my result need to be the documents that match the above two conditions.

Any pointers highly appreciated.

Upvotes: 0

Views: 81

Answers (1)

Sede
Sede

Reputation: 61225

Using the $where operator.

db.nodes.find(function() { 
    return (/^5:/.test(this._id) && Object.keys(this._revisions).length > 3 ); 
})

The problem with this as mentioned in the documentation is that:

$where evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g., $gt, $in).

You should definitely consider to change the _revisions field to an array of sub-documents like this:

{
    "_id" : "3:/content/somepath/test.txt",
    "_revisions" : [
        { 
            "rev": "r152f47f1daf-0-2",
            "value": "c"
        },
        {   
            "rev": "r152f48413c1-0-2",
            "value": "c"
        },
        {    
            "rev": "r152f4851bf7-0-1",
            "value": "c"
        }
    ]
}

And use the $exists operator.

db.nodes.find({ "_id": /^5:/, "_revisions.3": { "$exists": true } } )

Upvotes: 1

Related Questions