mongoDB:检查特定子文档数组

时间:2017-07-14 12:12:53

标签: mongodb database

我有以下架构:

{
_id: objectID('593f8c591aa95154cfebe612'),
name: 'test'
businesses: [
 {
  _id: objectID('5967bd5f1aa9515fd9cdc87f'),
  likes: [objectID('595796811aa9514c862033a1'), objectID('593f8c591ba95154cfebe790')]
 }
 {
  _id: objectID('59579ff91aa9514f600cbba6'),
  likes: [objectID('693f8c554aa95154cfebe146')]
 }
  ]
}

如何检查数据business.likes中是否存在objectID('593f8c591ba95154cfebe790')business._id = objectID('59579ff91aa9514f600cbba6')?

在上面的示例中,它应该返回false。

1 个答案:

答案 0 :(得分:0)

您可以使用$elemMatch在同一子文档中按多个字段查找

db.collectionName.find({
  businesses: {
    $elemMatch: {
      _id: ObjectId("5967bd5f1aa9515fd9cdc87f"),
      likes: ObjectId("593f8c591ba95154cfebe790")
    }
  }
});