我明白我的错误 :) 谢谢大家。 我还有一个问题,假设我在“客户”集合中有多个具有以下结构的文档。
{
"customerId":100,
"FirstName":"xyz",
"lastname":"pqr",
"address":[
{
"house":44,
"city":"Delhi",
"country":"india"
}
],
"employer":[
{
"cmpName":"ABC",
"type":"IT"
}
]
}
现在我有一个如下的 JSON 文件:
{
"customerId":100,
"address":[
{
"house":99,
"city":"MUMBAI",
"country":"INDIA"
}
]
}
您能否告诉我如何在我的 c# 代码中使用上述 JSON 文件更新 customerId = 100 的地址数组。
请推荐!
提前致谢:)
我正在编写一个 C# (C sharp)(.Net) 代码来在 mongoDB 中插入一个 JSON 文件。我有一个 jsonfile “records.JSON”,其中一行中有多个文档,例如:
[{"customerId" : 100,"FirstName" : "xyz","lastname" : "pqr","address":[{"house": 44,"city" : "Delhi", "country" : "india"}],"employer":[{"cmpName" : "ABC","type" : "IT"}]}][{"customerId" : 101,"FirstName" : "LMN","lastname" : "GHI","address":[{"house": 90,"city" : "NewYork", "country" : "US"}],"employer":[{"cmpName" : "ABC","type" : "IT"}]}]
我需要将此 JSON 文件插入到现有的 MongoDB 集合中。 到目前为止,我有以下代码可以连接并插入 mongodb:
public static void Main (string[] args)
{
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
server.Connect();
var database = server.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("test_collection");
string text = System.IO.File.ReadAllText(@"records.JSON");
var bsonDoc = BsonArray.Parse (text);
collection.Insert (bsonDoc);
}
但这给了我错误:“数组不能写入 BSON 文档的根级别”
如果我将 BSON 解析为: var bsonDoc = BsonDocument.Parse (text);
它给了我错误:Cannot deserialize BsonDocumet from BsonType Array.
任何人都可以帮助我了解如何将 JSON 文件插入到 mongoDB 集合中。 ??
任何帮助表示赞赏..提前致谢。
最佳答案
假设您有一个有效的 JSON 文件。
这是您需要做的,使用新的 MongoDB.Driver 2.0:
public static void Main (string[] args)
{
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var database = client.GetDatabase("test");
string text = System.IO.File.ReadAllText(@"records.JSON");
var document = BsonSerializer.Deserialize<BsonDocument>(text);
var collection = database.GetCollection<BsonDocument>("test_collection");
await collection.InsertOneAsync(document);
}
我希望它对你有用!
问候。
关于c# - 将 JSON 插入现有的 MongoDB 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29513174/