gerald-lindsly / mongo-delphi-driver

MongoDB Driver for Delphi
Apache License 2.0
47 stars 26 forks source link

Search document by "_id" #11

Closed drazde closed 7 years ago

drazde commented 7 years ago

I try to get a documey by its _id by this snippet, but it doesn't work!

  b := mongo.findOne(ns,(BSON(['_id','{','$oid','58c6b6af9b2dcd04ae46844d','}'])));
  if b = nil then
    ShowMessage('No match')
  else
    ShowRecord(b);

NB:

drazde commented 7 years ago

Ok, a guy give mi the answer on http://stackoverflow.com/questions/43777276/get-a-document-with-a-specific-id-with-mongo-delphi-driver/43777726?noredirect=1#43777726


var
  bb : TBsonBuffer;
  query, b : TBson;
  id : TBsonOID;
begin
  id := TBsonOID.Create('58c6b6af9b2dcd04ae46844d');
  bb := TbsonBuffer.Create();
  // _id isnt a json object it is an oid.
  bb.append('_id', id);
  query := bb.finish();
  b := mongo.findOne(ns, query);
  if b = nil then
    ShowMessage('No match')
  else
    ShowRecord(b);
end;