Get _id of an inserted document in MongoDB?

前端 未结 6 1852
渐次进展
渐次进展 2020-12-07 00:34

say I have a product listing. When I add a new product I save it using something like

var doc=products.Insert(p);

The pro

相关标签:
6条回答
  • 2020-12-07 00:47

    As the comment above, add the fild ID in your model with

    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string id { get; set; }
    

    using:

    using MongoDB.Bson;
    using MongoDB.Bson.Serialization.Attributes;
    

    and then when you insert the object, mongo return the ID of the document into the fild ID of the model.

    0 讨论(0)
  • 2020-12-07 00:47

    If you know the type of ID you can do something like this:

    public static TId GetId<TId>(this BsonDocument document) where TId : struct
    {
        if (document == default(BsonDocument))
        {
            throw new ArgumentNullException("document");
        }
    
        var id = document["_id"];
    
        object idAsObject;
    
        if (id.IsGuid)
        {
            idAsObject = (object)id.AsGuid;
        }
        else if (id.IsObjectId)
        {
            idAsObject = (object)id.AsObjectId;
        }
        else
        {
            throw new NotImplementedException(string.Format("Unknown _id type \"{0}\"", id.BsonType));
        }
    
        var idCasted = (TId)idAsObject;
    
        return idCasted;
    }
    

    Use it like this:

    Guid idOfDoc = myBsonDocument.GetId<Guid>();
    

    Still you should prefere have a dedicated property as in the chosen answer...

    0 讨论(0)
  • 2020-12-07 00:50

    When you insert an object into the mongodb, mongo will update the object with the internal ID.

    So if

    data = {
      title: "Howdy"
    }
    

    Then when we insert the data object into the db

    db.collection('collectionName', function(err, collection) {
      collection.insert(data);
      console.log(data._id); // <- The mongodb id is now set on the item
    });
    
    0 讨论(0)
  • 2020-12-07 00:51

    The Insert method automatically sets the property that is declared as the BSON ID of the model.

    If declared as follows...

    [BsonId]
    public ObjectId Id { get; set; }
    

    ... then the Id field will contain the default (new, unique) BSON ID of the object after inserting the object into a collection:

    coll.Insert(obj);
    // obj.Id is now the BSON ID of the object
    
    0 讨论(0)
  • 2020-12-07 00:59
    class BsonID
    {
        [BsonId]
        public ObjectId Id { get; set; }
    }
    var document = new BsonDocument {
       {"_id", new BsonID().Id },
       { "code", dr.Cells["code"].Value.ToString() },
       { "name", dr.Cells["name"].Value.ToString() },
      };
    var customers = _database.GetCollection<BsonDocument>("Customers");
    customers.InsertOne(document);
    var id = document.ElementAt(0).Value.ToString();
    
    0 讨论(0)
  • 2020-12-07 01:05

    I'm converting the custom type T to BsonDocument before persisting it.

    var bsonDocument = item.ToBsonDocument();
    _mongoCollection.InsertOne(bsonDocument);
    

    T has a property Id:

    [BsonId]
    public ObjectId Id { get; set; }
    

    When I call ToBsonDocument(), the Id field gets populated with ObjectId which gets pushed to Mongo DB.

    It creates the Id itself in the code instead of delegating to Mongo DB to create it. But it suffices my case.

    0 讨论(0)
提交回复
热议问题