dimanche 30 novembre 2014

How can I make parts of query criteria optional with MongoDB?


What I am looking to do here is two things:


I want to make every criteria in a query optional, and I want to sort the results of the query in descending order according to how many of the criteria matched? How can I do this?


For example, say my DB looks like this:



{ "_id" : ObjectId("547c127627cafb8f9838b06f"), "name" : "Things", "attributes" : { "a1" : "Foo", "a2" : "Foo", "a3" : "Foo" } }
{ "_id" : ObjectId("547c128227cafb8f9838b070"), "name" : "Stuff", "attributes" : { "a1" : "Foo", "a2" : "Foo", "a3" : "Bar" } }
{ "_id" : ObjectId("547c129427cafb8f9838b071"), "name" : "Blah", "attributes" : { "a1" : "Foo", "a2" : "Baz", "a3" : "Bar" } }
{ "_id" : ObjectId("547c12f627cafb8f9838b072"), "name" : "Other", "attributes" : { "a1" : "Quux", "a2" : "Baz", "a3" : "Bar" } }


If my query was something like {"attributes.a1": "Foo", "attributes.a2": "Foo", "attributes.a3": "Foo"} then I would want it to return, in order, the items with names Things, Stuff, and then Blah. How would I accomplish this?





Aucun commentaire:

Enregistrer un commentaire