How to use dot in field name?

后端 未结 7 1178
一整个雨季
一整个雨季 2020-11-30 07:19

How to use dot in field name ?

I see error in example:

db.test2.insert({ \"a.a\" : \"b\" })

can\'t have . in field names [a.a]
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 08:01

    I've only really come across this problem when trying to serialize Dictionaries and such where the offending dot can appear as a key name. Edited to show the references.

    The quick and dirty C# approach:

    using MongoDB.Bson;
    using Newtonsoft.Json.Linq;
    using System.Text.RegularExpressions;
    
    public static T Sanitize(T obj)
    {
          var str = JObject.FromObject(obj).ToJson();
          var parsed = Regex.Replace(str, @"\.(?=[^""]*"":)", "_");   //i.e. replace dot with underscore when found as a json property name { "property.name": "don't.care.what.the.value.is" }
          return JObject.Parse(parsed).ToObject();
    }
    

提交回复
热议问题