软件下载吧文章资讯

分类分类

mongo数据集合属性中存在点号(.)的解决方法

2024-02-24 17:17作者:下载吧

前言

MongoDB是面向集合存储的文档型数据库,其涉及到的基本概念与关系型数据库比有所不同。本文主要介绍关于mongo数据集合属性存在点号(.)的相关内容,下面话不多说了,来一起看看详细的介绍吧

基本知识点:

1.似乎mongo3.6之前不允许插入带点(.)或美元符号($)的键,但是当我使用mongoimport工具导入包含点的JSON文件时,它工作正常。

2.在使用spring-data-mongodb处理mongodb的增删改查时会通过一个MappingMongoConverter(Document和Modle转换类)转换数据

3.具体对点号的转换在DBObjectAccessor(spring-data-mongodb-1.10.13)或者DocumentAccessor(spring-data-mongodb-2.0.9),如下:

//插入时转换
public void put(MongoPersistentProperty prop, Object value) {
Assert.notNull(prop, “MongoPersistentProperty must not be null!”);
String fieldName = prop.getFieldName();
if (!fieldName.contains(“.”)) {
dbObject.put(fieldName, value);
return;
}
Iterator<String> parts = Arrays.asList(fieldName.split(“\.”)).iterator();
DBObject dbObject = this.dbObject;
while (parts.hasNext()) {
String part = parts.next();
if (parts.hasNext()) {
dbObject = getOrCreateNestedDbObject(part, dbObject);
} else {
dbObject.put(part, value);
}
}
}

//查询时转换
public Object get(MongoPersistentProperty property) {
String fieldName = property.getFieldName();
if (!fieldName.contains(“.”)) {
return this.dbObject.get(fieldName);
}
Iterator<String> parts = Arrays.asList(fieldName.split(“\.”)).iterator();
Map<String, Object> source = this.dbObject;
Object result = null;
while (source != null && parts.hasNext()) {
result = source.get(parts.next());
if (parts.hasNext()) {
source = getAsMap(result);
}
}
return result;
}

//判断值是否为空
public boolean hasValue(MongoPersistentProperty property) {
Assert.notNull(property, “Property must not be null!”);
String fieldName = property.getFieldName();
if (!fieldName.contains(“.”)) {
return this.dbObject.containsField(fieldName);
}
String[] parts = fieldName.split(“\.”);
Map<String, Object> source = this.dbObject;
Object result = null;
for (int i = 1; i < parts.length; i++) {
result = source.get(parts[i – 1]);
source = getAsMap(result);
if (source == null) {
return false;
}
}
return source.containsKey(parts[parts.length – 1]);
}

展开全部

相关文章

说两句网友评论
    我要跟贴
    取消