I’m trying to search in mongodb for articles based on tags:
> use test;
> db.articles.save( { name: "article1", tags: ['one', 'two', 'three'] } );
> db.articles.save( { name: "article2", tags: ['two', 'three'] } );
> db.articles.save( { name: "article3", tags: ['one', 'three'] } );
> db.articles.save( { name: "article4", tags: ['one', 'two', 'four'] } );
> db.articles.save( { name: "article5", tags: ['four', 'five'] } );
> db.articles.ensureIndex( { tags: 1 } );
> db.articles.find( { $or : [ { tags: 'four' }, { tags: 'five' } ] } )
{ "_id" : ObjectId("509d7b555bff77729a26a232"), "name" : "article4", "tags" : [ "one", "two", "four" ] }
{ "_id" : ObjectId("509d7b555bff77729a26a233"), "name" : "article5", "tags" : [ "four", "five" ] }
As you can see the query looks for “four” or “five”, but I would like to get the results sorted by “best match” (two tags matched are better than one tag matched).
How can I get this done? map reduce?
Thanks in advance:
xabi
I am really sorry to disappoint you but there is nothing mongo can do right now.
The only option is to implement sorting on the application side. I know that this can be too inefficient but there is no other option.
The only thing I can help you with is to suggest to substitute
to
this will not help you with your query (I mean to order results), but it will be easier to you to create it on the server if there will be a lot of different tags.