Mongodb提供了多种开发语言的驱动,java,python,c++,c# 等,这里选用c#驱动作为测试;
using MongoDB.Bson;
using MongoDB.Driver;
protected staticIMongoClient client;
protected staticIMongoDatabase database;
protected staticIMongoCollection collection;
//定义连接
client = new MongoClient("mongodb://127.0.0.1:27017");
//获取test数据库
database = client.GetDatabase("test");
//获取test数据库中的集合bios
collection = database.GetCollection("bios");
var document =new BsonDocument
{
{ "address" , newBsonDocument
{
{ "street","2 Avenue" },
{ "zipcode","10075" },
{ "building","1480" },
{ "coord",new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan"},
{ "cuisine", "Italian"},
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date",new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade","A" },
{ "score",11 }
},
new BsonDocument
{
{ "date",new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade","B" },
{ "score",17 }
}
}
},
{ "name", "Vella"},
{ "restaurant_id","41704620" }
};方法;
最终插入结果:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace mongodbInsert
{
class Program
{
protected static IMongoClient client;
protected static IMongoDatabase database;
protected static IMongoCollection collection;
static void Main(string[] args)
{
client = new MongoClient("mongodb://127.0.0.1:27017");
database = client.GetDatabase("test");
collection = database.GetCollection("bios");
for (int i = 0; i < 14; i++)
{
var document = new BsonDocument
{
{ "address" , new BsonDocument
{
{ "street", "2 Avenue" },
{ "zipcode", "10075" },
{ "building", "1480" },
{ "coord", new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan" },
{ "cuisine", "Italian" },
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "A" },
{ "score", 11 }
},
new BsonDocument
{
{ "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "B" },
{ "score", 17 }
}
}
},
{ "name", "Vella" },
{ "restaurant_id", "41704620" }
};
collection.InsertOneAsync(document);
}
Console.WriteLine();
Console.ReadLine();
}
}
}