Search code examples
mongodbmongodb-querymongodb-.net-driver

Search full document in mongodb for a match


Is there a way to match a value with every array and sub document inside the document in mongodb collection and return the document

{
  "_id" : "2000001956",
  "trimline1" : "abc",
  "trimline2" : "xyz",
  "subtitle"  : "www",
  "image" : {
    "large" : 0,
    "small" : 0,
    "tiled" : 0,
    "cropped" : false
  },     
  "Kytrr" : {
      "count" : 0,
      "assigned" : 0
  }

}

for eg if in the above document I am searching for xyz or "ab" or "xy" or "z" or "0" this document should be returned.

I actually have to achieve this at the back end using C# driver but a mongo query would also help greatly.

Please advice.

Thanks


Solution

  • While Malcolm's answer above would work, when your collection gets large or you have high traffic, you'll see this fall over pretty quickly. This is because of 2 things. First, dropping down to javascript is a big deal and second, this will always be a full table scan because $where can't use an index.

    MongoDB 2.6 introduced text indexing which is on by default (it was in beta in 2.4). With it, you can have a full text index on all the fields in the document. The documentation gives the following example where a text index is created for every field and names the index "TextIndex".

    db.collection.ensureIndex(
        { "$**": "text" },
        { name: "TextIndex" }
    )