Get _id of an inserted document in MongoDB?

2019-01-20 07:49发布

问题:

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

var doc=products.Insert<ProductPDO>(p);

The problem is that I want after this is done to redirect the user to the page with the product. So I need to redirect to say /products/<ObjectID>

However, I see no way of getting the ObjectID right afterwards without manually querying the database and look for a document with all the same fields and such.

Is there an easier way? (also, doc in this instance returns null for some reason)

回答1:

You can check the id field of the inserted document. It should be filled in.

Edited by asker:

Just to be clear, in order to make an id field in your own classes you just use:

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


回答2:

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


回答3:

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.



回答4:

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...