You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# MongoDB模型中声明数组的数组(Azure Cosmos DB场景)

解决方案

首先,你需要先定义一个用于表示单个坐标的实体类,用来映射JSON里的lat和lon字段:

namespace GeofencedLocations.Models
{
    public class Coordinate
    {
        [BsonElement("lat")]
        public string Latitude { get; set; }
        
        [BsonElement("lon")]
        public string Longitude { get; set; }
    }
}

接下来修改Geofence类中的LocationCoordinates字段类型,将其改为Coordinate类型的集合(数组或泛型列表都可以):

namespace GeofencedLocations.Models
{
    public class Geofence
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string LocationId { get; set; }
        
        [BsonElement("Location name")]
        public string LocationName { get; set; }
        
        [BsonElement("Location Coordinates")]
        // 可以用数组或者 List<Coordinate>,根据需求选择
        public Coordinate[] LocationCoordinates { get; set; }
        // 或者泛型列表写法:public List<Coordinate> LocationCoordinates { get; set; }
        
        [BsonElement("user ID")]
        public string userID { get; set; }
    }
}

说明

  • 定义Coordinate类是为了和你提供的JSON结构精准映射,每个坐标对象对应lat和lon两个字符串字段
  • 选择数组还是List<Coordinate>取决于业务场景:泛型列表在增删元素时更灵活,数组适合固定长度的坐标集合
  • 保留BsonElement特性能确保实体类属性和Cosmos DB(MongoDB API)中的字段名一一对应

内容的提问来源于stack exchange,提问作者Muskan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:57:18