karel lahmy
karel lahmy

Reputation: 417

MongoDB - Sort results by number of matched fields

Assuming I have a very simple collection with only firstName and lastName fields, and I am searching using this query:

{"$or:[{"firstName":"John"},{"lastName":"Smith"}]}

How can I sort the results so I will get the documents that were matched both John and Smith first and then just John or just Smith? do I need to use aggregation for that?

Thanks.

Upvotes: 1

Views: 293

Answers (2)

Victor Schröder
Victor Schröder

Reputation: 7777

Well, I think you'll need to use aggregation. I would use a query like this:

db.yourcollection.aggregate([

    /* Match documents with firstName == "John" OR lastName == "Smith" */
    {
        $match:{
            $or:[
                {firstName:"John"},
                {lastName:"Smith"}
            ]
        }
    },

    /* Project data creating a new field named "good".
       With the comparisons good will be true if
       firstName == "John" AND lastName == "Smith" */
    {
        $project:{
            _id:1,
            firstName:1,
            lastName:1,
            good:{
                $and:[
                    {$eq:["$firstName","John"]},
                    {$eq:["$lastName","Smith"]}
                ]
            }
        }
    },

    /* Sort by "good", descending, so true values come first */
    {$sort:{good:-1}}
])

Upvotes: 1

Zaid Masud
Zaid Masud

Reputation: 13463

Although text indexes in v2.4 are still an experimental feature, I believe it will give you what you are looking for.

If you create a text index weighting both firstName and lastName equally, the query result will be in descending order of score with the highest score matching both fields.

Upvotes: 0

Related Questions