How to read back automatically generated identifier from mongo after pasting using official C # driver?

after you enter a new document in mongodb through the official C # driver, how do you immediately read the generated _id so that I can use it as a β€œforeign” key for other collections? I know in sql server, I can immediately read the value of the identifier column for the newly inserted row, so I need similar functionality in mongodb.

since the _id generated by mongo is not an actual member of the object, suppose you need to do something with a generic bsondocument?

+4
source share
5 answers

You can do upsert with the findAndModify command to achieve the same effect with less work than creating your own identifiers. (Why worry, there is a very good reason 10gen decided to use sceme, which makes scalding easy)

The findAndModify command allows you to find or update (create if it does not exist) a document and return the same document.

The general view is as follows:

db.runCommand( { findAndModify : <collection>, <options> } ) 

Learn more about this here .

You would like to use the new addition to the upsert option to return a newly created object.

+2
source

In MongoDB, identifiers are (usually) generated on the client side. And you can create it yourself, using the appropriate driver call, insert it into the document, and it will be saved.

I did not work with the C # driver, but the Ruby driver does all the work for me.

 ruby-1.9.3-p0 :027 > obj = coll.insert({'foo' => 'bar'}) => BSON::ObjectId('4ef15e7f0ed4c00272000001') ruby-1.9.3-p0 :030 > coll.find.to_a => [{"_id"=>BSON::ObjectId('4ef15e7f0ed4c00272000001'), "foo"=>"bar"}] 

Here is how I can create a new ID

 ruby-1.9.3-p0 :039 > newid = BSON::ObjectId.new => BSON::ObjectId('4ef15f030ed4c00272000002') ruby-1.9.3-p0 :040 > coll.insert({_id: newid, test: 'test'}) => BSON::ObjectId('4ef15f030ed4c00272000002') ruby-1.9.3-p0 :041 > coll.find.to_a => [{"_id"=>BSON::ObjectId('4ef15e7f0ed4c00272000001'), "foo"=>"bar"}, {"_id"=>BSON::ObjectId('4ef15f030ed4c00272000002'), "test"=>"test"}] 
0
source

If you need _id, you can create it yourself and set it manually in the document.

0
source

In most drivers, the _id field _id actually created on the client side before moving to the server. MongoDB does not use the identifier "auto-increment", so you can generate a random identifier and tell the server to "use this".

In C #, the code is as follows:

 var id = ObjectId.GenerateNewId(); 

So you can create a BSON document and just save it:

 var toSave = new BsonDocument { { "_id", ObjectId.GenerateNewId() }, { "data", "my data" } }; db.collection.Save(toSave); 

However, by default, when you .Save() in a document, this will update the _id field. That way, you can just save the BSONDocument (or BSONSerializable ) class and then read it back.

Note that there is a DBRef specification that simplifies the implementation of "foreign keys." The docs here in C # you will want to look at the DBRef class.

0
source

Like the other answers here, identifiers are assigned on the client side. Something you can do is create a default convention that generates a new identifier during insertion, if it is not already set.

 public class DefaultValueConvention : MongoDB.Bson.Serialization.Conventions.IDefaultValueConvention { public object GetDefaultValue(MemberInfo memberInfo) { var type = memberInfo.MemberType == MemberTypes.Property ? ((PropertyInfo) memberInfo).PropertyType : ((FieldInfo) memberInfo).FieldType; if (type.IsSubclassOf(typeof(ObjectId))) return ObjectId.GenerateNewId(); else return null; } } 

And configure the driver to use this convention:

 var profile = new ConventionProfile(); profile.SetDefaultValueConvention(new DefaultValueConvention()); BsonClassMap.RegisterConventions(profile, x => x.FullName.StartsWith("ConsoleApplication")); 

So now you can create an object and save it in two lines:

 var animal = new Animal {Name = "Monkey", PercentDeviationFromHumans = 2.01}; db["animals"].Save(animal); 

Actually, with the latest driver, you don’t even need to set a standard default agreement, it already has this OOTB behavior. Despite this, agreements in mangoes are not used enough.

0
source

Source: https://habr.com/ru/post/1387313/


All Articles