基本知识点:
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]);
- }
4.点号在mongodb中有子集合的含义
例如查询A.B属性:查询的是集合中A对应子集合中的属性B的值,并不是查询集合中A.B的属性
问题描述:文档在数据库中的样子:
- {
- "_id": ObjectId("5bae00765500af6307755111"),
- "name": "java",
- "age": 26,
- "A.B": "nnnn"
- }
- 因此在Model中使用@Field("A.B")查询不出集合中的"A.B"的值
- @Field("A.B")
- @JSONField(serialzeFeatures = SerializerFeature.DisableCircularReferenceDetect)
- private Integer ab;
5.解决方法:
查阅多方资料有以下几点体会:点号在MongoDB中可以插入应该开始于3.6版本,官方文档虽然说可以支持点号,但是第三方驱动、spring-data-mongodb并没有支持,但是因为一开始项目已经使用了spring-data-mongodb难以替换,所以就想到覆盖转换方法。
怎么覆盖spring-data-mongodb包中的文件?
新建一个和DBObjectAccessor转换文件一样的目录,重新建DBObjectAccessor类复制代码自定义修改,编译之后或优先使用新建的类。
- //查询时转换
- public Object get(MongoPersistentProperty property) {
- String fieldName = property.getFieldName();
- return this.dbObject.get(fieldName);
- }
-
- //判断值是否为空
- public boolean hasValue(MongoPersistentProperty property) {
- Assert.notNull(property, "Property must not be null!");
- String fieldName = property.getFieldName();
- return this.dbObject.containsField(fieldName);
- }
注意:尽量不要修改put方法,应为低版本的MongoDB本不支持点号,插入会报错
当然最好不要发生属性中有点号的情况。