如何使用 c# 驱动程序 mongodb 获取文档的 id [英] How to get the id of a document using c# driver mongodb

查看:78
本文介绍了如何使用 c# 驱动程序 mongodb 获取文档的 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从一个文档中获取 id 才能将其放入另一个文档中,但我无法做到这一点.我已经尝试了很多次,但结果很糟糕.如果有人可以提供帮助.

I need to take the id from a document to put it into another one, but i can't achieve this. I've tried many times but i get bad results. If someone could help.

这是我的控制器:

    public ActionResult LancerComparaison(ResultViewModel resultViewModel)
    {
        if (resultViewModel!= null)
        {
            UserInformationViewModel info = resultViewModel.UserInformationViewModel;
            var client = new MongoClient("mongodb://localhost:27017");
            var objDatabase = client.GetDatabase("Test");
            var collection = objDatabase.GetCollection<BsonDocument>("UsersInformations");
            BsonDocument objDocument = new BsonDocument {
            {"Nom",info.NomUser},
            {"Prenom",info.PrenomUser},
            {"Email",info.EmailUser},
            };
            collection.InsertOne(objDocument);
            var id = objDocument.{_id}
            List<ObjetTransfert> listePrestationsObjetsTransferts = new List<ObjetTransfert>();
            ResultatComparaison resultatComparaison;
            ConvertGViewModelToGBd(resultViewModel, listePrestationsObjetsTransferts);
            _compaSBT.ComparerP(listePrestationsObjetsTransferts, out resultatComparaison,
                Enums.E.T);

            //Enregistrer d'abord le resultat en Bd
            resultatComparaison.IdentifiantResultatComparaison = new Guid().ToString();
            resultatComparaison.IdentifiantUserInformation = id.ToString();
            _resultatComparaisonService.Create(resultatComparaison);

            Session["IdentifiantResultatComparaison"] = resultatComparaison.Id;


            return View();
        }
        return null;
    }

推荐答案

当你保存新文档时,你的 Bson Id 被设置在执行后 InsertOne 方法传递的同一个文档中.

when you save new document your Bson Id is set inside the same document passed by InsertOne method after the execution.

 collection.InsertOne(objDocument);
 var id = objDocument.{yourBsonIdProp}

希望对你有帮助.

这篇关于如何使用 c# 驱动程序 mongodb 获取文档的 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆