【问题标题】:how to find specific string in key value pair in mongodb如何在mongodb的键值对中查找特定字符串
【发布时间】:2013-02-13 23:18:11
【问题描述】:

我在 mongodb 中有这样的数据

[

{
  "name":"silvester",
  "product":"laptop,iphone,mobile,phone"
},

{
   "name":"john",
   "product":"cycle,bus,phone,laptop"
},

{
   "name":"franklin",
   "product":"cycle,phone"
}

]

如何找到笔记本电脑在产品密钥中。 如果产品密钥看起来像这样

{
"name":"XXX",
"product":"laptop"
}

我可以使用db.collection.find("product":"laptop"); 轻松找到该名称

那么如何找到这个呢?

另外让我知道这三个使用backbone.js和node.js和mongodb技术运行的网站名称,例如www.trello.com。 对不起我最糟糕的英语..

【问题讨论】:

  • “产品”是数组还是字符串或逗号分隔的元素?
  • 下面发布的解决方案是否不适合您?
  • 您应该将 product 存储为字符串数组,因为 Mongo 针对这种情况进行了优化。其他任何事情都会慢得多。

标签: node.js mongodb


【解决方案1】:

Using regex with mongodb

这对我有用

db.collection.find({"product": /laptop/})

更新答案

如果您想使用变量,请尝试以下操作:

var abc = "laptop";
// other stuff
userdetails.find({"product":new RegExp(abc)}).toArray(function(err,result){
  if (err) console.log ("error: "+err);
  else 
  {    
    // if you want the length
    console.log(result.length);
    // if you actually want to see the results
    for (var i = 0; i < result.length; i++)
    {
      console.log(result[i]);
    }
  }
}); 

又更新了一次

var abc = "laptop";
// other stuff

// note this is case sensitive.  if abc = "Laptop", it will not find it
// to make it case insensitive, you'll need to edit the RegExp constructor
// to this: new RegExp("^"+abc+",|, "+abc+"(?!\w)", "i")

userdetails.find({"product":new RegExp("^"+abc+",|, "+abc+"(?!\w)")}).toArray(function(err,result){
  if (err) console.log ("error: "+err);
  else 
  {    
    // if you want the length
    console.log(result.length);
    // if you actually want to see the results
    for (var i = 0; i < result.length; i++)
    {
      console.log(result[i]);
    }
  }
}); 

【讨论】:

  • 我宁愿改变模式以使产品字段成为字符串数组,这将使您能够使用该字段的索引并显着提高查询性能。与当前版本一样,您每次都将浏览整个集合。
  • 我已经动态地给出了这个 var abc=laptop; userdetails.find({"product":"/"+abc+"/"}).toArray(function(err,result){console.log(result.length)});但我只有零长度,所以如何动态地做到这一点?
  • 我更新了我的答案。如果此解决方案适合您,请考虑接受。
  • 即使我给了 l 而不是笔记本电脑,我也会得到输出,但我只希望输出确切的笔记本电脑而不是 l 或 la 或 lap
  • 请注意,这个问题实际上并没有解决。将来最好为您的新问题创建一个新问题。我继续编辑我的帖子以反映您可以做什么。我相信这应该有效。但是,我坚信您真的应该研究 @vittore 的建议。
【解决方案2】:

正则表达式可以正常工作。还有一个好消息,monogdb 将在即将发布的版本中发布全文搜索索引

http://docs.mongodb.org/manual/release-notes/2.4/#text-indexes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多