marcino0o
marcino0o

Reputation: 313

MongoDB findOne query depends of result

lets say that I have collection of something and record can look like that:

{
    '_id' : MongoId('xxxxxx'),
    'dir' : '/home/',
    'category' : 'catname',
    'someData' : 'very important info'
}

Is it possible to make only one query like collection.findOne({????}, {'someData' : 1}); to find colection matching this:

find by dir, if not found search for category name, if there is still nothing find collection with category name is 'default'

or at least, can I say in this query that I want first match dir and if not found I want match category

collection.findOne({
    $or : [
        {'dir' : 'someCondition'},
        {'category' : 'someCondition'}
    ]
});

Upvotes: 1

Views: 77

Answers (1)

SolarBear
SolarBear

Reputation: 4629

Try this:

db.collection.aggregate([
    { '$project':
        {
            //Keep existing fields
            '_id':1,
            'dir':1,
            'category':1,
            'someData':1,
            //Compute some new values
            'sameDir': {'$eq':['$dir', 'SOMEDIR']},
            'sameCategory': {'$eq':['$dir', 'SOMECATEGORY']},
            'defaultCategory': {'$eq':['$dir', 'default']},
        }
    },
    { '$sort':
        {
            'sameDir': -1,
            'sameCategory': -1,
            'defaultCategory': -1,
        }
    },
    { '$limit': 1 }
])

The $sort will keep true values first, so a directory match will come first, followed by a category match, finally followed by a default category. The $limit:1 will keep the one on top (ie. the best match). Of course, make sure to input your own SOMEDIR and SOMECATEGORY values.

Upvotes: 1

Related Questions