不废话先代码:
import org.bson.BsonObjectId;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
@Test
void findById() {
String _id = "60c1c9d0f6207b275012b3e0";
Query query = Query.query(
Criteria.where("_id").is(new BsonObjectId(new ObjectId(_id)))
);
System.out.println(
reactiveMongoTemplate
.findOne(query, TestDocument.class)
.block()
);
}
试了一下午,比较了一下compass和java发包的区别,发现各种论坛直接使用new ObjectId(_id)产生的数据流和String是相似的,id会变成对应的asc码,而正确的格式应该是字符串对应的十六进制数
错误数据:
正确数据:
尝试了一些数据类型,均不可行,于是从insert方法中寻找答案,最后发现了下面的代码,尝试使用BsonObjectId查到了结果
package com.mongodb.internal.operation;
final class Operations<TDocument> {
MixedBulkWriteOperation bulkWrite(final List<? extends WriteModel<? extends TDocument>> requests,
final BulkWriteOptions options) {
if (writeModel instanceof InsertOneModel) {
TDocument document = ((InsertOneModel<TDocument>) writeModel).getDocument();
if (getCodec() instanceof CollectibleCodec) {
// 此处生成ObjectId
document = ((CollectibleCodec<TDocument>) getCodec()).generateIdIfAbsentFromDocument(document);
}
// 此处ObjectId转为BsonObjectId
writeRequest = new InsertRequest(documentToBsonDocument(document));
}
}
}