marcXandre
marcXandre

Reputation: 2432

Filter within Mongo embedded document by range

I have a mongo collection that looks like this:

{
    '_id': '...',
    'friends': {
        'id1': {'name': 'john', 'dateAdded': ISODate(...)},
        'id2': {'name': 'joe', 'dateAdded': ISODate(...)},
         ...
    }
}

I will like to filter the collection by friends attribute dateAdded without changing the collection model.

Is there an operator that makes filtering inside an embedded document dictionary possible?

Where the query will look like this:

self.collection.find({
    'friends.$operator.dateAdded': {
        '$gte': datetime.datetime(2000, 1, 1),
        '$lte': datetime.datetime(2001, 9, 1)
    }
})

Upvotes: 0

Views: 97

Answers (1)

Belly Buster
Belly Buster

Reputation: 8814

There is no operator to perform what you are asking. In (very) simplistic terms, think of MongoDB as key/value store; you need to know the key in order to determine the value.

If you have the option to, refactor your schema so that friends is an array and lose the ids. In general it is poor design to have arbitrary-named keys such as id[n].

Upvotes: 1

Related Questions