Mongodb 在 Java 中将 .Net GUID 转换为 BinData

我正在使用 Mongo .Net 驱动程序在 MongoDB 中插入文档,我需要使用 Java 驱动程序获取文档。


我的型号:


public class Person{

 public Guid Id {get;set;}

 public Guid FatherId{get;set;}

 public string Name{get;set;}

}

我正在使用以下 C# 代码向 MongoDb 插入一个文档。


var id= Guid.NewGuid();

Persons.InsertOne(new Person(){Id = id,Name = "Joe"});

现在,有了 id,如何使用 Mongo Java 驱动程序找到相同的文档?我试过:


Person person=Persons.find(eq("_id", id))).first();

但是我没有得到任何结果,我已经研究过了,似乎在使用 find 之前应该将 id 转换为 Base64。


所以我尝试了以下方法:


 public String uuidToBase64(String str) {

    java.util.Base64.Encoder encoder=Base64.getUrlEncoder();

    UUID uuid = UUID.fromString(str);

    ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);

    uuidBytes.putLong(uuid.getMostSignificantBits());

    uuidBytes.putLong(uuid.getLeastSignificantBits());

    return encoder.encodeToString(uuidBytes.array());

}


Person person=Persons.find(eq("_id", BinData(3,uuidToBase64(id))))).first();

那还是不行。


幕布斯6054654
浏览 235回答 1
1回答

aluckdog

对于其他人的参考,根据答案,以下内容对我有用:首先将 id 转换为字符串类型。&nbsp; Document doc = mongoCollection&nbsp; &nbsp; .find(eq("_id", new Binary((byte) 3, Base64.getDecoder().decode(uuidToBase64(id)))))&nbsp; &nbsp; .first();编码方式:&nbsp; public static String uuidToBase64(String str) {&nbsp; &nbsp; &nbsp; &nbsp; java.util.Base64.Encoder encoder=Base64.getEncoder();&nbsp; &nbsp; &nbsp; &nbsp; UUID uuid = UUID.fromString(str);&nbsp; &nbsp; &nbsp; &nbsp; ByteBuffer bb = ByteBuffer.wrap(new byte[16]);&nbsp; &nbsp; &nbsp; &nbsp; bb.putLong(uuid.getMostSignificantBits());&nbsp; &nbsp; &nbsp; &nbsp; bb.putLong(uuid.getLeastSignificantBits());&nbsp; &nbsp; &nbsp; &nbsp; byte[] java=bb.array();&nbsp; &nbsp; &nbsp; &nbsp; byte[] net= new byte[16];&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 8; i < 16; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; net[i] = java[i];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; net[3] = java[0];&nbsp; &nbsp; &nbsp; &nbsp; net[2] = java[1];&nbsp; &nbsp; &nbsp; &nbsp; net[1] = java[2];&nbsp; &nbsp; &nbsp; &nbsp; net[0] = java[3];&nbsp; &nbsp; &nbsp; &nbsp; net[5] = java[4];&nbsp; &nbsp; &nbsp; &nbsp; net[4] = java[5];&nbsp; &nbsp; &nbsp; &nbsp; net[6] = java[7];&nbsp; &nbsp; &nbsp; &nbsp; net[7] = java[6];&nbsp; &nbsp; &nbsp; &nbsp; return encoder.encodeToString(net);}
打开App,查看更多内容
随时随地看视频慕课网APP