- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using MongoDB.Driver;
- using Models;
- using MongoDB.Bson;
- namespace MongoDbTest {
- class Program {
- private static string _MongoDbConnectionStr = "mongodb://yjq:[email protected]:27017/admin";
- static void Main(string[] args) {
- var productCollection = GetCollection();
- //添加一个待审核的商品
- //Product product = new Product("苹果", (decimal)5.20);
- //productCollection.InsertOne(product);
- //Console.WriteLine($"添加商品:{product.ToString()}成功。");
- //批量增加商品
- List productAddList = new List();
- for (int i = 0; i < 100; i++) {
- productAddList.Add(GetRandomProduct());
- }
- productCollection.InsertMany(productAddList);
- var productList = productCollection.Find(new BsonDocument()).ToList();
- foreach(var item in productList) {
- Console.WriteLine(item.ToString());
- }
- Console.Read();
- }
- private static IMongoCollection GetCollection(string collectionName = null) {
- MongoUrl mongoUrl = new MongoUrl(_MongoDbConnectionStr);
- var mongoClient = new MongoClient(mongoUrl);
- var database = mongoClient.GetDatabase(mongoUrl.DatabaseName);
- return database.GetCollection(collectionName ? ?typeof(T).Name);
- }
- private static string[] _ProductNames = new string[] {
- "苹果",
- "香蕉",
- "菠萝",
- "哈密瓜",
- "西瓜",
- "黄瓜",
- "草莓",
- "桃子",
- "芒果",
- "猕猴桃",
- "梨"
- };
- private static Random rn = new Random();
- private static Product GetRandomProduct() {
- var i = rn.Next(_ProductNames.Length);
- decimal price = i * 15;
- var enumValue = rn.Next(1, 5);
- return new Product(_ProductNames[i], price, (ProductSaleState) enumValue);
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2081098.html