以名称+值的形式读取 MongoDB 数据时出现问题

问题描述 投票:0回答:1

我正在使用 C# 从 MongoDB 读取数据,我遇到了一种情况,其中一个键的数据:

GoodsList
正在以这种形式读取:

{
  "goodsList": [
    [
      {
        "name": "name",
        "value": "testName"
      },
      {
        "name": "price",
        "value": 32
      },
      {
        "name": "number",
        "value": 1
      },
      {
        "name": "id",
        "value": 68345
      },
      {
        "name": "cate_id",
        "value": 6208
      },
      {
        "name": "image",
        "value": "/testimg.png"
      },
      {
        "name": "use_property",
        "value": 1
      },
      {
        "name": "props_text",
        "value": "standardtext,standardtext2"
      },
      {
        "name": "props",
        "value": [
          582,
          585
        ]
      }
    ]
  ]
}

但我不想要这个,我希望它以下面的格式阅读:

{
  "StatusText": "Finished",
  "GoodsList": [
    {
      "name": "testName",
      "price": 32,
      "number": 1,
      "id": 68345,
      "cate_id": 6208,
      "image": "/testimg.png",
      "use_property": 1,
      "props_text": "standardtext,standardtext2",
      "props": [
        582,
        585
      ]
    }
  ],
  "Notes": "this.form.remark",
}

如何设置正确的阅读格式?我尝试将其读取为

BsonArray
BsonDocument
或直接作为实体类(实体类中的
GoodsList
BsonArray
BsonDocument
),但它不起作用,要么出现转换错误或者结果还是一样。

c# mongodb mongodb-.net-driver
1个回答
1
投票

正如评论中提到的,您应该创建自己的模型类,

GoodsList
也是如此。

当您使用

BsonArray
/
BsonDocument
并序列化结果时,它将显示包含
Key
Value
属性的对象。

您的模型类应如下所示:

using MongoDB.Bson.Serialization.Attributes;

[BsonNoId]
public class Goods
{
    [BsonElement("name")]
    public string Name { get; set; }

    [BsonElement("price")]
    public int Price { get; set; }

    [BsonElement("number")]
    public int Number { get; set; }

    [BsonElement("id")]
    public int Id { get; set; }

    [BsonElement("cate_id")]
    public int CateId { get; set; }

    [BsonElement("image")]
    public string Image { get; set; }

    [BsonElement("use_property")]
    public int UseProperty { get; set; }

    [BsonElement("props_text")]
    public string PropsText { get; set; }

    [BsonElement("props")]
    public List<int> Props { get; set; }
}

public class Root
{
    public ObjectId Id { get; set; }

    [BsonElement("StatusText")]
    public string StatusText { get; set; }

    [BsonElement("GoodsList")]
    public List<Goods> GoodsList { get; set; }

    [BsonElement("Notes")]
    public string Notes { get; set; }
}
IMongoDatabase db = /* IMongoDatabase instance */;
IMongoCollection<Root> collection = db.GetCollection<Root>("<collection name>");

var result = collection.Find(/* Filter criteria */)
    .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.