node.js - 如何在mongodb中查找键值对中的特定字符串

标签 node.js mongodb

我在 mongodb 中有这样的数据

[

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

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

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

]

如何查找产品 key 中的笔记本电脑。 如果产品 key 看起来像这样

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

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

那么如何找到这个呢?

同时让我知道这三个使用backbone.js和node.js以及mongodb技术运行的网站名称,例如www.trello.com。 抱歉我的英语最差..

最佳答案

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]);
    }
  }
}); 

关于node.js - 如何在mongodb中查找键值对中的特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14815621/

相关文章:

php - doctrine ODM 加载相关文档导致查询过多

mysql - 使用nodejs和数据库存储GPS纬度和经度的最佳方式

mongodb - 如何将primitive.m 断言为map[string]string

algorithm - Mahout 基于内容的推荐引擎

mongodb - AWS CLI 的细微差别

node.js - 与 Slack 的 RTM API 的 websocket 连接出现 404

javascript - 如何在 Angular 指令中使用 React 自定义包

javascript - 如何修复 Three.js 加载超过 2 分钟并崩溃的问题

node.js - 对另一个sequelize 查询的每个结果运行Sequelize 原始查询

node.js - Electron --serve在缺少package.json时失败