蒙戈 bson 插入/读取子记录

本文关键字:记录 读取 bson 插入 蒙戈 | 更新日期: 2023-09-27 18:31:29

我想插入一条带有子项的记录,然后用 c# 在屏幕上显示写入的内容。这是我到目前为止所拥有的:

    MongoCollection<BsonDocument> house= building.GetCollection<BsonDocument>("house");
    BsonDocument rooms= new BsonDocument {
                { "roomName", name},
                { "location",  <--child array here: 1stfloor, 2ndlfloor, topfloor.
                { "roomID", guidstring}
                };
    house.Insert(rooms);

蒙戈 bson 插入/读取子记录

你的意思是用于调试目的吗?为此,您可以将文档转换为 JSON 字符串:

Console.WriteLine(rooms.ToJson());

您还可以使用 mongo shell 查看您的文档。运行 mongo shell,然后键入:

> use buildings // or whatever your database name is
> db.house.find()
... your documents displayed here
> 

如果您的集合包含大量文档,则可能需要包含某种查询以缩小显示的文档范围。

还应考虑使用 C# 类定义域模型,并让驱动程序为您在 BSON 文档之间相互转换。