3

I am using Mongo .Net driver to insert documents in MongoDB, and I need to get the documents using Java driver.

My Model:

public class Person{
 public Guid Id {get;set;}
 public Guid FatherId{get;set;}
 public string Name{get;set;}
}

And I am inserting a document to MongoDb using the following C# code.

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

Now, having the id, how can I find the same document using Mongo Java driver? I tried:

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

But I am not getting any result, I have researched it and it seems like id should be converted to Base64 before using find.

So I tried the following:

 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();

That still did not work.

Yahya Hussein
  • 8,767
  • 15
  • 58
  • 114

1 Answers1

0

For others reference, based on the answer, the following worked for me:

first convert id to string type.

  Document doc = mongoCollection
    .find(eq("_id", new Binary((byte) 3, Base64.getDecoder().decode(uuidToBase64(id)))))
    .first();

Encoding Method:

  public static String uuidToBase64(String str) {
        java.util.Base64.Encoder encoder=Base64.getEncoder();
        UUID uuid = UUID.fromString(str);
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());
        byte[] java=bb.array();
        byte[] net= new byte[16];
        for (int i = 8; i < 16; i++) {
            net[i] = java[i];
        }
        net[3] = java[0];
        net[2] = java[1];
        net[1] = java[2];
        net[0] = java[3];
        net[5] = java[4];
        net[4] = java[5];
        net[6] = java[7];
        net[7] = java[6];
        return encoder.encodeToString(net);
}
Yahya Hussein
  • 8,767
  • 15
  • 58
  • 114