2

I have a search field in my application which I would like to query my collection in multiple ways. The search query which is input by the user needs to match either the name field or the url field. For example, a document that looks like this:

{ "name": "Google Maps", "url": "http://maps.google.co.uk/" }

Should be matched if I input goog, //maps, maps google, etc. – you get the picture. Just a case insensitive regex search on multiple fields.

I know how to use regex to search a field for a case insensitive value, but I'm new to MongoDB (and databases in general) and I'm not sure what the best solution would be for this. Do I need to implement a "compound index"? If so, how do I query against that index for the two fields?

4

1 回答 1

0

Split your input by spaces then add each to the list of queries to $or:

db.collection.find({
  $or: {
    [
      {name: /goog/i},
      {url: /goog/i},
      {name: /\/\/maps/i},
      {url: /\/\/maps/i}
    ]
  }
})

In node:

var query = "maps google";
var ors = [];
query.split(" ").forEach(function(q) {
  ors[] = {name: new RegExp(q)};
  ors[] = {url: new RegExp(q)};
});
db.collection.find({$or: {ors} })
于 2013-03-30T22:56:28.787 回答