Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 28th, 2012  |  syntax: None  |  size: 1.51 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. MongoDB query: how to check if a string stored in a document is contained in another string
  2. StringInDb = "this is a string"
  3. TheOtherString = "this is a long string that contains this is a string"
  4.        
  5. from s in DB.Table
  6. where TheOtherString.IndexOf(s.StringInDb ) > -1
  7. select s.StringInDb;
  8.        
  9. var map =
  10.   "function() {" +
  11.   "    for (var key in this) {" +
  12.   "        emit(key, { count : 1 });" +
  13.   "    }" +
  14.   "}";
  15.  
  16. var reduce =
  17.   "function(key, emits) {" +
  18.   "    total = 0;" +
  19.   "    for (var i in emits) {" +
  20.   "        total += emits[i].count;" +
  21.   "    }" +
  22.   "    return { count : total };" +
  23.   "}";
  24.  
  25. var mr = collection.MapReduce(map, reduce);
  26. foreach (var document in mr.GetResults()) {
  27.   Console.WriteLine(document.ToJson());
  28. }
  29.        
  30. var query = Query.Matches("StringParamName",
  31.      BsonRegularExpression.Create("*this is a string*", "-i"));
  32.        
  33. /// <summary>
  34. /// Makes a Bson object for current value object
  35. /// </summary>
  36. /// <returns>The Bson object for current value object</returns>
  37. private BsonValue GetBsonValue()
  38. {
  39.     if (!_value.Contains(_wildCard))
  40.         return _value;
  41.     string pattern = ApplyWildCard();
  42.     return BsonRegularExpression.Create(new Regex(pattern, RegexOptions.IgnoreCase));
  43. }
  44.  
  45. /// <summary>
  46. /// Finds wildcard characters and substitutes them in the value  string
  47. /// </summary>
  48. /// <returns></returns>
  49. private string ApplyWildCard()
  50. {
  51.     return string.Format("^{0}$", _value.Replace(_wildCard, ".*"));
  52. }
  53.        
  54. public QueryComplete BuildQuery()
  55.     {
  56.         return Query.EQ(_key, GetBsonValue());
  57.     }