首页  编辑  

Mongodb嵌套数组元素的匹配查询

Tags: /Java/   Date Created:
$ elemMatch(查询)_MonogDB 中文网 (mongodb.net.cn)
MongoDB嵌套数组,多维数组查询_criteria.where().elemmatch()-CSDN博客

一、嵌套数组
数据:
{
  "arrays": [
    {
      "keyArrays": [
        {
          "key": "index",
          "key2": "index2"
        },
        {
          "key": "index1",
          "key2": "index2"
        }
      ]
    }
  ]
}
mongo语法
db.collection.find({arrays:{$elemMatch:{keyArrays:{$elemMatch:{key:"index", key2:"index2"}}}}}) 
java写法 
Criteria criteria = Criteria.where("arrays.keyArrays").elemMatch(Criteria.where("key").is("index").and("key2").is("index1")); 
 
二、多维数组
数据:
{
  "arrays": [
    [
      {
        "key": "index"
      },
      {
        "key": "index1"
      }
    ]
  ]
}
 mongo语法
db.collection.find({arrays:{$elemMatch:{$elemMatch:{key:"index"}}}})
java写法 
Criteria criteria = Criteria.where("arrays").elemMatch(new Criteria().elemMatch(Criteria.where("key").is("index")));