单文档插入


db.inventory.insertOne(  
        { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)

如果该集合当前不存在,则插入操作将创建该集合。

多文档插入



db.inventory.insertMany([
        { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }, 
        { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
        { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
    ])

在MongoDB中,存储在集合中的每个文档都需要一个唯一的 _id字段作为主键。 如果插入的文档省略_id字段,则MongoDB驱动程序会自动为_id字段生成ObjectId。

2. 查询文档

db.inventory.insertMany([
  { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
  { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
  { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
  { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
  { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);

以上代码是插入数据的代码,下面查询文档

Find All:

    db.inventory.find( {} )

它翻译成SQL是

    SELECT * FROM inventory

= 操作:

    db.inventory.find( { status: "D" } ) 

它翻译成SQL是

    SELECT * FROM inventory WHERE status = "D"

IN 操作:

   db.inventory.find( { status: { $in: [ "A", "D" ] } } )

它翻译成SQL是

    SELECT * FROM inventory WHERE status in ("A", "D")

尽管可以使用 $or 操作符来满足上述需求,但是在对相同字段进行等值检索的时候更建议使用 $in

AND 操作:

   db.inventory.find( { status: "A", qty: { $lt: 30 } } )

它翻译成SQL是

   SELECT * FROM inventory WHERE status = "A" AND qty < 30

OR 操作:

  db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )

它翻译成SQL是

  SELECT * FROM inventory WHERE status = "A" OR qty < 30

$lt 是小于的意思

同时使用AND和OR条件:

  db.inventory.find( {
     status: "A",
     $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )

它翻译成SQL是

 SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")

db.collection.findOne 方法提供了返回单个文档的读操作。
实际上,db.collection.findOne 就是db.collection.find() 方法后面加了个限制条数1。

/^p/ 是转成p%,因为 ^ 在正则中是以 某某开头的意思,所以这里可以理解成 / 就是%

    db.bios.findOne(
    {
        $or: [
                { 'name.first' : /^G/ },
                { birth: { $lt: new Date('01/01/1945') } }
            ]
    }
    )

它翻译成SQL是

    SELECT TOP 1 * FROM bios WHERE [name.first] LIKE 'P%' OR birth < '1945-01-01'

有关字段的返回问题

find 方法接受两个参数,第一个Json参数是需要查询的条件,第二个Json参数是需要映射的字段。

    db.connections.find({},{})

字段映射有两种方式,第一种是需要什么字段就写在后面,如 {name:1,age:1,phone:1},这个的意思是只返回name、age、phone这三个字段。

第二种是不需要什么字段,如 {birth:0}意思是除了birth字段以外的字段都需要返回。

    /* 返回 item 和 qty 字段 */
    db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )

    /* 返回 item 和 qty 字段,但不要带上 _id 这个字段 */
    db.inventory.find( { type: 'food' }, { item: 1, qty: 1, _id:0 } )

    /* 返回 除了 type 以外的所有字段 */
    db.inventory.find( { type: 'food' }, { type:0 } )

3.文档更新

主要使用一下方法:


    db.collection.udpateOne(<filter>,<udpate>,<options>)

    db.collection.udpateMany(<filter>,<udpate>,<options>)

    db.collection.replaceOne(<filter>,<udpate>,<options>) 

接下来是一个例子:


    db.inventory.updateOne(
        { item: "paper" },
        {
            $set: { "size.uom": "cm", status: "P" }, 
            $currentDate: { lastModified: true }
        }
    )   

更新item等于 paper的文档,设置 "size.uom" 字段为 cm ,status 为 p,并设置 lastModified 字段为当前时间,这里用到了 $set 和 $currentDate 。在本例中如果 “size.uom” 不存在则创建,如果lastMondified不存在也会创建。翻译成SQL应该是这样的:

    --前提是这个查询条件只返回一条数据

    UPDATE inventory SET [size.uom] = 'cm',status='p',lastModified = getdate()
    WHERE item = 'paper'

更新多个文档:


  db.inventory.updateMany( 
      { "qty": { $lt: 50 } },
      {  
          $set: { "size.uom": "in", status: "P" }, 
          $currentDate: { lastModified: true }  
      }
  )

更新qty < 50 的文档,设置 "size.uom" 字段为 "in" ,status 为 p,并设置 lastModified 字段为当前时间,这里用到了 $set 和 $currentDate 。在本例中如果 “size.uom” 不存在则创建,如果lastMondified不存在也会创建。翻译成SQL应该是这样的:

    UPDATE inventory SET [size.uom] = 'cm',status='p',lastModified = getdate()
    WHERE qty < 50

在 C# 中的事务操作


// For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.

// string uri = "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl";

// For a sharded cluster, connect to the mongos instances; e.g.

// string uri = "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/";

var client = new MongoClient(connectionString);

// Prereq: Create collections.

var database1 = client.GetDatabase("mydb1");

var collection1 = database1.GetCollection<BsonDocument>("foo").WithWriteConcern(WriteConcern.WMajority);

collection1.InsertOne(new BsonDocument("abc", 0));

var database2 = client.GetDatabase("mydb2");

var collection2 = database2.GetCollection<BsonDocument>("bar").WithWriteConcern(WriteConcern.WMajority);

collection2.InsertOne(new BsonDocument("xyz", 0));

// Step 1: Start a client session.
using (var session = client.StartSession())
{
    // Step 2: Optional. Define options to use for the transaction.
    var transactionOptions = new TransactionOptions(
        readPreference: ReadPreference.Primary,
        readConcern: ReadConcern.Local,
        writeConcern: WriteConcern.WMajority);

    // Step 3: Define the sequence of operations to perform inside the transactions
    var cancellationToken = CancellationToken.None; // normally a real token would be used
    result = session.WithTransaction(
        (s, ct) =>
        {
            collection1.InsertOne(s, new BsonDocument("abc", 1), cancellationToken: ct);
            collection2.InsertOne(s, new BsonDocument("xyz", 999), cancellationToken: ct);
            return "Inserted into collections in different databases";
        },
        transactionOptions,
        cancellationToken);
}

相关文章: