java objectid,如何使用Java使用ObjectIds创建查询?

"博客讨论了在使用MongoDB进行查询时遇到的问题。作者指出,查询语句未能正确匹配_id字段,原因是ObjectId对象的构建方式。尽管查询结构看似正确,但实际应当避免使用`"$oid"`关键字。解决方案是确保查询中的ObjectId与数据库中的格式一致。建议检查服务器连接、数据库和集合名称以确认无误。"
摘要由CSDN通过智能技术生成

I have set of ids like:

["51eae104c2e6b6c222ec3432", "51eae104c2e6b6c222ec3432", "51eae104c2e6b6c222ec3432"]

I need to find all documents using this set of ids.

BasicDBObject query = new BasicDBObject();

BasicDBList list = new BasicDBList();

ObjectId ob1 = new ObjectId("51eae100c2e6b6c222ec3431");

ObjectId ob2 = new ObjectId("51eae100c2e6b6c222ec3432");

list.add(ob1);

list.add(ob2);

query.append("_id", new BasicDBObject("$in", list));

This query can't find anything because it is same as

{ "_id" : { "$in" : [ { "$oid" : "51eae100c2e6b6c222ec3431"} , { "$oid" : "51eae100c2e6b6c222ec3432"}]}}

To find something it must be

{_id:{$in:[ObjectId("51eae100c2e6b6c222ec3431") , ObjectId("51eae104c2e6b6c222ec3432")]}}

but I don't know how to make ObjectId("51eae100c2e6b6c222ec3431") in list using java

解决方案

{ "$oid" : "51eae100c2e6b6c222ec3431"} is the same as ObjectId("51eae100c2e6b6c222ec3431") just in a different format.

If the query is not finding any documents (and you are sure they are present in the collection) then there is some other issue. I would double check the server(s) you are connecting to and the name of the database and collection first.

Rob.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值