Aneek
Aneek

Reputation: 145

Searching multiple fields in mongodb

I have a mongo collection. Now a user can search using any field or all of the fields based on his needs.

For example :- A user can search using any one of attribute or any two attribute or any number of attribute he remembers of the fields present in the collection. Help me to decide which operator or combination of operators should I use?

{"_id":1, "field1":"hi","field2":"bye","field3":"bro", "field4":"stuff"},
{"_id":2, "field1": "hello", "field2": "back", "field3": "fat", "field4":"cat"},
{"_id":3, "field1": "some", "random": "foo", "stuff": "bar", "field4":"help"}

Upvotes: 2

Views: 12538

Answers (3)

Jeet
Jeet

Reputation: 5659

Here you go -

db.test.find({
$or:[
    {
        $and: [
                {'stocknumber':12346},
                {'model':'bmx'},
                {'make':2002},
                {'rego':'KA01HG6268'},
                {'adate':'2017-10-01T05:07:10.969Z'},
                {'cdate':'2017-10-01T05:07:10.969Z'}
            ]
    },
    {
        $and: [
                {'stocknumber':12347},
                {'model':'bmy'},
                {'make':2003}
            ]

    }
]
}).pretty()

You can use combination of $and and $or in the above example $or acts as umbrella operator which let you execute any one query which ever combination user remembers, each query contains an $and operator which helps you to create combinations of fields user remember. This is going to be a lengthy query but better then a lot of null checks and string manipulation. In worst case it would be a Cartesian product of number of fields and both the operator. Hope this helps.

Upvotes: 5

Alex P.
Alex P.

Reputation: 3171

You'd have to wrap your parameters, that the user can search for, around an $or. Then every field that could be searched for has to use the $in operator.

db.getCollection('collection').find({
    $or: [
    {field1: {$in: ["hi", "hello", "some"]}},
    {field2: {$in: ["bye", "back", "some"]}},
    {field3: {$in: ["bye", "back", "some"]}},
    // etc. add your other fields as well here
    ]
})

Upvotes: 3

Antti_M
Antti_M

Reputation: 968

In MongoDB, you can make queries with and/or clauses.

For instance:

db.collection.find( { $or: [ { field1: "hi" }, { field1: "hello" } ] } )

Upvotes: 1

Related Questions