
前言:
不知道有没有和小名一样,接触MongDB时间不长的小伙伴。由于MongoDB是以文档形式存储数据的,所以其中的数据类型相对MySql或者Oracle关系型数据库丰富一些(MongoDB是NoSQL数据库这里比较不是很准确)
我们在关系型数据库中查询非空数据习以为常(例如:where id <> “”),但是到了MongoDB中出现了“数组”这种存储格式,而且,数组又存在一维数组和二维数组,当我们在需求中遇到“查询二维数组不为空”时,这就让一些不熟悉MongDB的小伙伴头痛了。
所以小名将平时用过的一些查询MongoDB中不为空的方法分享给大家,希望大家用得到:
文章目录
- 一、MongoDB查询数组不为空
- 二、示例
- 1. MongoDB查询数组不为空
- 2. MongoTemplate查询数组不为空
 
首先我们先来看MongoDB中的查询方式:
一、MongoDB查询数组不为空
- $elemMatch和- $ne
db.Collection.find({array:{$elemMatch:{$ne:null}}})
- $where
db.Collection.find({$where:"this.array.length>0"})
- $not和- $size
db.Collection.find({array: {$not: {$size: 0}}})
- ‘.’路径和- $exists
db.Collection.find({{'array.0': {$exists: 1}}})
- $exists和- $ne
db.Collection.find({ array: { $exists: true, $ne: [] } })
- $gt
db.Collection.find({ array: { $gt: [] } })
二、示例
我们先来看下数据结构
{
    "_id" : "1",
    "prodectList" : [ 
        {
            "prodectId" : "001",
            "prodectName" : "保温杯",
            "price" : "29.90",
            "salesChannelsList" : [ 
                {
                    "channel" : 0,
                    "price" : "0"
                }, 
                {
                    "channel" : 1,
                    "price" : "4.90"
                }, 
                {
                    "channel" : 2,
                    "price" : "0"
                }, 
            ]
        }
    ],
    "deleteFlg" : 0,
}
1. MongoDB查询数组不为空
MongoDB查询一维数组查询其中包含的值
db.getCollection('PHO_PRODECT').find({"salesChannelsList":{$elemMatch:{$eq:0}}})
MongoDB按条件查询嵌套数组
db.getCollection('PHO_PRODECT').find({"prodectList.salesChannelsList":{$elemMatch:{"channel":1,"price" : "4.90"}}})
MongoDB查询二维数组不为空
db.getCollection('PHO_PRODECT').find({"prodectList.salesChannelsList.0":{$exists:true}})
2. MongoTemplate查询数组不为空
MongoTemplate查询二维数组不为空
queryItem.addCriteria(Criteria.where("prodectList.salesChannelsList.length").gt(0));
MongoTemplate查询一维数组不为空
queryItem.addCriteria(Criteria.where("salesChannelsList.0").exists(true));

















