Java中的mongodb查询id
我在MongoDB集合中有一个Json文档,我想根据_id查询它
{
"_id": {
"$oid": "102e8484f2caba7e805dc334"
},
"customerName": "TESLA",
"customerInfo": {
"name": "Elon",
},
"createdDate": {
"$date": "2021-02-19"
},
"modifiedDate": {
"$date": "2021-02-18T15:19:00.586Z"
},
"status": "DRAFT",
}
现在我有了一个工作代码,如果我查询任何其他不是系统生成的json密钥(比如status或customerInfo.name),我就能够得到预期的结果
但我用_id或$date做的所有试验都不起作用。我试着在多个帖子中寻找答案,但都没有成功。以下是我在问这个问题之前尝试过的搜索选项:
import static com.mongodb.client.model.Filters.eq;
// above import used below.
MongoCursor<Document> cursor = collection.find(eq(key, value)).iterator();
where
key="_id.$oid"
value= byID (passed as say "123123121"
eq("_id.$oid", byID)
eq("_id.oid", byID)
eq("_id", byID)
eq("oid", byID)
eq("oid", ObjectId(byID)) - this gives compile errors.
非常感谢您的帮助
# 1 楼答案
在Slack上找到了这个答案(我发现这个答案是有效的——测试正常):How to query documents using "_id" field in Java mongodb driver?
作者@bogolyandras,标题为“对于那些寻求更新方法的人,尤其是3.4:”