【问题标题】:Search if providing id is exist on Multiple objects under array mongodb搜索数组 mongodb 下的多个对象上是否存在提供 id
【发布时间】:2017-11-08 17:43:21
【问题描述】:

我的数据库有这个值

id: ObjectId(6a00683bac41ce1054774e7d),
currentuserid: "69fc06dbf88c8c15042b4e36",
dataset: Array
 0: Object
   userid: "69fc06dbf88c8c15042b4e37"

 1: Object
   userid: "69fc06dbf88c8c15042b4e38"

2: Object
   userid: "69fc06dbf88c8c15042b4e39"

现在我想查询哪个首先检查“currentuserid”是否存在于数组下。如果值存在则返回 true 否则返回 false。我是 mongodb 的新手。我还阅读了 $in Operator 。我的查询是

Mydata.find({ dataset: { $in: [{userid: '69fc06dbf88c8c15042b4e36'}] } }, function(req, res){
  if(err){ console.log('Not Matched'); }
  else{ console.log('Matched') }
});

但我无法实现它

【问题讨论】:

  • .find({ "dataset.userid": '69fc06dbf88c8c15042b4e36' })$in 用于“参数数组”而不是“检查数组”。 MongoDB 不在乎值在数组中。它所需要的只是正确的“路径”。
  • 那么先生,我怎样才能做到这一点?
  • 使用我实际给你的确切查询。阅读"dot notation" 并了解原因。继续阅读有关查询的所有教程。

标签: node.js mongodb


【解决方案1】:

试试这个:

Mydata.findOne({dataset:{$elemMatch:{userid:'69fc06dbf88c8c15042b4e37'}}},function(err, data){
  if(err){ 
    throw err; 
  } else if(data){ 
    console.log('Matched');
  }else{
    console.log('Not Matched')
  }  
});

它将导致用户 ID 69fc06dbf88c8c15042b4e36的数据为空。

【讨论】:

  • 不,不会这样。它总是在两种情况下运行,即“匹配”
  • 我的文档结构如下: { "_id" : ObjectId("5a02e6bb6a0755f9e9aac29c"), "currentuserid" : "69fc06dbf88c8c15042b4e36", "dataset" : [ { "userid" : "69fc06dbf88c8c15042b4" } {“用户标识”:“69fc06dbf88c8c15042b4e38”},{“用户标识”:“69fc06dbf88c8c15042b4e39”}]}
  • 可能类似于:var _userId = "69fc06dbf88c8c15042b4e36" Mydata.findOne({currentuserid: _userId, dataset:{$elemMatch:{userid:_userId}}},function(err, data){ if (err){ throw err; } else if(data){ console.log('Matched'); }else{ console.log('Not Matched') } });
猜你喜欢
  • 1970-01-01
  • 2019-08-03
  • 2020-06-17
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 2021-09-03
  • 2014-03-12
相关资源
最近更新 更多