2

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

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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
    ]
})

Comments

1

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

For instance:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.