Mongodb快速入门

创建数据库

使用数据库quickstart, 如果数据库不存在, 则创建数据库

use quickstart

插入数据

db.students.insert({"name": "laggage", "age": 21})

查找数据

db.students.find()

result:

{ "_id" : ObjectId("5f8aaeb8a2d37d24c77cea57"), "name" : "laggage", "age" : 21 }
{ "_id" : ObjectId("5f8aaf1fa2d37d24c77cea58"), "name" : "tom", "age" : 21 }
{ "_id" : ObjectId("5f8aaf32a2d37d24c77cea59"), "name" : "xixi", "age" : 21 }
{ "_id" : ObjectId("5f8aaf3da2d37d24c77cea5a"), "name" : "jack", "age" : 22 }

查找年龄21的Student

db.students.find({"age": 21})

result:

{ "_id" : ObjectId("5f8aaeb8a2d37d24c77cea57"), "name" : "laggage", "age" : 21 }
{ "_id" : ObjectId("5f8aaf1fa2d37d24c77cea58"), "name" : "tom", "age" : 21 }
{ "_id" : ObjectId("5f8aaf32a2d37d24c77cea59"), "name" : "xixi", "age" : 21 }

更新数据

db.students.update({"name": "laggage"}, {$set: {"name": "laggage-updated"}})

result:

> db.students.find()
{ "_id" : ObjectId("5f8aaeb8a2d37d24c77cea57"), "name" : "laggage-updated", "age" : 21 }
{ "_id" : ObjectId("5f8aaf1fa2d37d24c77cea58"), "name" : "tom", "age" : 21 }
{ "_id" : ObjectId("5f8aaf32a2d37d24c77cea59"), "name" : "xixi", "age" : 21 }
{ "_id" : ObjectId("5f8aaf3da2d37d24c77cea5a"), "name" : "jack", "age" : 22 }

删除数据

删除 name 为 laggage-updated 的student

db.students.remove({"name": "laggage-updated"})

result:

> db.students.remove({"name": "laggage-updated"})
WriteResult({ "nRemoved" : 1 })
> db.students.find()
{ "_id" : ObjectId("5f8aaf1fa2d37d24c77cea58"), "name" : "tom", "age" : 21 }
{ "_id" : ObjectId("5f8aaf32a2d37d24c77cea59"), "name" : "xixi", "age" : 21 }
{ "_id" : ObjectId("5f8aaf3da2d37d24c77cea5a"), "name" : "jack", "age" : 22 }

dotnet中操作mongodb

我的环境:

win10 with powershell
vs code with extensions ["vscode-solution-explorer", "C#"]

创建控制台项目

mkdir MongoWithDotnet ; cd MongoWithDotnet

dotnet new sln -n MongoWithDotnet

dotnet new console -n MongoWithDotnet

dotnet sln .MongoWithDotnet.sln add .MongoWithDotnetMongoWithDotnet.csproj

安装 MongoDB.Driver 包引用

dotnet add .MongoWithDotnetMongoWithDotnet.csproj package MongoDB.Driver

dotnet restore .MongoWithDotnetMongoWithDotnet.csproj

简单的增删改查

数据实体Student
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace MongoWithDotnet
{
    public class Student
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        [BsonElement("name")]
        public string Name { get; set; }

        [BsonElement("age")]
        public uint Age { get; set; }

        public override string ToString()
        {
            return $"{Name}, {Age}岁";
        }
    }
}
mongodb增删改查
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Driver;

namespace MongoWithDotnet
{
    class Program
    {
        // 连接字符串
        public const string ConnectionString = "mongodb://<user nam,e>:<passoword>@localhost:27017/quickstart?authSource=admin";

        private MongoClient _client;

        public Program()
        {
            _client = new MongoClient(ConnectionString);

            var collection = _client.GetDatabase("quickstart").GetCollection<Student>("students");

            // 清空数据先
            var result = collection.DeleteMany(stu => true);
            Console.WriteLine($"Clear db, {result.DeletedCount} items deleted");
            
            // 准备测试数据
            collection.InsertMany(new Student[] {
                new Student
                {
                    Name = "tom",
                    Age = 21
                },
                new Student
                {
                    Name = "lucy",
                    Age = 21
                },
                new Student
                {
                    Name = "peipei",
                    Age = 25
                },
                new Student
                {
                    Name = "tutu",
                    Age = 24
                },
                new Student
                {
                    Name = "qiqi",
                    Age = 27
                },
            });

            // 查询所有学生
            Console.WriteLine("All students:");
            DisplayStudents(collection.AsQueryable());
            Console.WriteLine("// --------- //");
            // --------- //
        
            // 查询年龄大于21的学生
            Console.WriteLine("Students whose age over 21:");
            DisplayStudents(collection.AsQueryable().Where(stu => stu.Age > 21));
            Console.WriteLine("// --------- //");
            // --------- //

            // 插入数据
            collection.InsertOne(new Student{ Name = "dotnet test user", Age = 23 });
            Console.WriteLine("All students:");
            DisplayStudents(collection.AsQueryable());
            Console.WriteLine("// --------- //");
            // --------- //
            
            // 修改名称为 dotnet test user 的学生
            var stu = collection.AsQueryable().FirstOrDefault(stu => stu.Name == "dotnet test user");
            stu.Name = "modified dotnet test user";
            stu.Age = 32;
            collection.ReplaceOne(s => s.Name == "dotnet test user", stu);
            Console.WriteLine("All students:");
            DisplayStudents(collection.AsQueryable());
            Console.WriteLine("// --------- //");
            // --------- //

            // 删除名称为 modified dotnet test user 的学生
            collection.DeleteOne(s => s.Name == "modified dotnet test user");
            Console.WriteLine("All students:");
            DisplayStudents(collection.AsQueryable());
            Console.WriteLine("// --------- //");
            // --------- //
        }

        private void DisplayStudents(IEnumerable<Student> students) => students.ToList().ForEach(stu => Console.WriteLine(stu));

        static void Main(string[] args)
        {
            new Program();
        }
    }
}

需要注意的是mongodb的每个数据库可以分别配置不同的用户名和密码, 如果要用admin数据库的用户名和密码登陆到其他数据库, 那么链接字符串需要制定authSource=admin, mongodb://<user nam,e>:<passoword>@localhost:27017/quickstart?authSource=admin

原文地址:https://www.cnblogs.com/Laggage/p/13871533.html