• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

MongoDB和MongoTemplate对于嵌套数据的判空查询

武飞扬头像
进阶的小名
帮助3

学新通

前言:

不知道有没有和小名一样,接触MongDB时间不长的小伙伴。由于MongoDB是以文档形式存储数据的,所以其中的数据类型相对MySql或者Oracle关系型数据库丰富一些(MongoDB是NoSQL数据库这里比较不是很准确)

我们在关系型数据库中查询非空数据习以为常(例如:where id <> “”),但是到了MongoDB中出现了“数组”这种存储格式,而且,数组又存在一维数组和二维数组,当我们在需求中遇到“查询二维数组不为空”时,这就让一些不熟悉MongDB的小伙伴头痛了。

所以小名将平时用过的一些查询MongoDB中不为空的方法分享给大家,希望大家用得到:

首先我们先来看MongoDB中的查询方式:

一、MongoDB查询数组不为空

  1. $elemMatch $ne
db.Collection.find({array:{$elemMatch:{$ne:null}}})
  1. $where
db.Collection.find({$where:"this.array.length>0"})
  1. $not $size
db.Collection.find({array: {$not: {$size: 0}}})
  1. ‘.’ 路径和 $exists
db.Collection.find({{'array.0': {$exists: 1}}})
  1. $exists $ne
db.Collection.find({ array: { $exists: true, $ne: [] } })
  1. $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));

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfbcecb
系列文章
更多 icon
同类精品
更多 icon
继续加载