[CXX-887] Create an example of getting _id's from insert results Created: 01/Apr/16  Updated: 11/Sep/19  Resolved: 14/Jun/16

Status: Closed
Project: C++ Driver
Component/s: API
Affects Version/s: None
Fix Version/s: 3.0.2

Type: Task Priority: Major - P3
Reporter: Armin Ball [X] Assignee: Unassigned
Resolution: Done Votes: 0
Labels: c++11, neweng
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: HTML File retVal3_DBPointer    

 Description   

Hey there,

I'm using c++11 driver and going to extract the Hex-ID of a youst inserted document with the function collection.insert_one.

Is there a function I can coll to extract the ID out of the returned Object?
Can't find any example.

struct core::v1::optional<mongocxx::v_noabi::result::insert_one> retVal3 = collection.insert_one(document.view());

std::string = retVal3.IDplease(); // or the hex code. anything? =)



 Comments   
Comment by Githook User [ 14/Jun/16 ]

Author:

{u'username': u'xdg', u'name': u'David Golden', u'email': u'xdg@xdg.me'}

Message: CXX-887 Add inserted_id example
Branch: master
https://github.com/mongodb/mongo-cxx-driver/commit/0dd4f144c7421a0701f41529e1177274d9d93ac0

Comment by Armin Ball [X] [ 08/Jun/16 ]

cool =)
this will help a lot of newbees!

Comment by David Golden [ 06/Jun/16 ]

https://github.com/mongodb/mongo-cxx-driver/pull/491

Comment by Andrew Morrow (Inactive) [ 11/Apr/16 ]

Weltenbummler - Yes we would of course be interested in taking a pull request with a new example if you are interested in submitting one. You will need to sign the MongoDb contributor agreement.

Comment by Armin Ball [X] [ 08/Apr/16 ]

I thank you for your support!
When I finnished my current work I can upload parts of it as a example. If you like?
Best reguards! =)

Comment by Matt Cotter [ 07/Apr/16 ]

Hi Armin,

Try something like this:

bsoncxx::builder::stream::document filter_document{};
bsoncxx::oid object_id{"57059999b6a7d1308754e7c1"};
filter_document << "_id" << object_id;
std::cout << "Document:" << std::endl << bsoncxx::to_json(filter_document.view()) << std::endl;

It prints:

Document:
{
    "_id" : {
        "$oid" : "57059999b6a7d1308754e7c1"
    }
}

The $oid is just a way that we represent object id's in pure JSON (because using the "_id" : ObjectId("5705918cb6a7d12aea0525f1") is not true json, but extended json).

I am going to retitle this ticket to add an example for the code snippet I posted to the examples folder in the repository.

For any future bug reports, please open new tickets. Thanks again for using the driver!

-Matt

Comment by Armin Ball [X] [ 07/Apr/16 ]

Hey there,

I'm going to get the document withe the ID 57040cd5b6a7d149e30537b3 from my database.

I tried:

    //filter_builder << "_id" << open_document << "oid" << "57040cd5b6a7d149e30537b3" << close_document;
    //filter_builder << "_id" << open_document << "oid" << "ObjectId(\"5705918cb6a7d12aea0525f1\")" << close_document;
    //filter_builder << "_id" << open_document << "$oid" << "57040cd5b6a7d149e30537b3" << close_document;	//what():  Can't canonicalize query: BadValue unknown operator: $oid: generic server error
    //filter_builder << "_id" << open_document << $oid << "57040cd5b6a7d149e30537b3" << close_document;
    //filter_builder << "target" << open_document << "type" << "s3" << close_document;
	

nothing worked. To get to this attempt I spend some hours. Maybe you could solve my problem some more faster than me ?
I'm pretty sure I'm running in the wrong direction. Because last line also did not work. So it has nothing to do with the $.
Is there a more easy way to get an item if i know only one is existing?

the structure is like:

{
    "_id" : {
        "$oid" : "57059999b6a7d1308754e7c1"
    }, 
    "target" : {
        "type" : "s3", 
        "s3bucket" : "bucketname", 
        "s3region" : "BBn"
    }

Btw. what is the meaning of the "$oid" ?
In JSON it looks like:
"_id" : ObjectId("5705918cb6a7d12aea0525f1"),

Comment by Armin Ball [X] [ 06/Apr/16 ]

Dear Matt,

thank you for your lines.
I'm also new to such complex libraries. Maybe I'm running into those problems again.
Where can I start in looking for the right function in the source file of the libraries?
Or at which topic should I look in my C++ - book to get some useful informations out of this?

I already have some questions left:

result optional is engaged ("true")
this is saying, that I should check:

if( result != NULL ) {...} //?


Is this the only way to catch the error?

How should I test the Type?
#include <typeinfo>

if ( typeid(result) == "bsoncxx::types::value" );

How can I find that function, you just introduced to me?
Searching for the sring "inserted_id" leads me to this most promising result.
In "result/insert_one.cpp" --> line 31/32:

nconst bsoncxx::types::value& insert_one::inserted_id() const {
    return _generated_id;
}

what tells me, that this is a function that I can use on the returning type of: auto db = conn["test"]["log"]; where can I look for in the library source files?

All the best!
Armin Ball

Comment by Armin Ball [X] [ 05/Apr/16 ]

You can't believe how glad I'm right now!

Inserted id:57040cd5b6a7d149e30537b3
{
    "MessageType" : "blubb"
}

Comment by Matt Cotter [ 05/Apr/16 ]

Hi Weltenbummler,

Great question! I think the inserted_id() method of the result::insert_one class is what you are looking for. Here's an example:

#include <iostream>
 
#include <mongocxx/client.hpp>
#include <mongocxx/exception/operation_exception.hpp>
#include <mongocxx/instance.hpp>
 
int main(int, char**) {
    mongocxx::instance inst{};
    mongocxx::client conn{mongocxx::uri{}};
 
    bsoncxx::builder::stream::document document{};
 
    auto collection = conn["test"]["col"];
    document << "test" << 1;
 
    auto result = collection.insert_one(document.view());
    bsoncxx::oid id = result->inserted_id().get_oid().value;
    std::string id_str = id.to_string();
    std::cout << "Inserted id: " << id_str << std::endl;
}

Note, to be safe here, you want to double check that the result optional is engaged ("true") before accessing into it, and also that the bsoncxx::types::value returned from inserted_id() has the right type before calling get_oid(). Let me know if this answers your question!

Best,
-Matt

Comment by Armin Ball [X] [ 02/Apr/16 ]

Maybe this is the wrong place. please inform me, if so.

Generated at Wed Feb 07 22:00:40 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.