mongodb 插入資料

liiinuuux發表於2015-04-03
> db.createCollection("obj");
{ "ok" : 1 }

插入一個文件
> db.obj.insert({
...   name: "obj1",
...   arr: [{elemName: "elem1", elemValue: 1}, {elemName: "elem2", elemValue: 2}],
...   subObj: {
...       subName: "subName1",
...       subArr: ["subElem1", "subElem2", "subElem3"]
...     }
...   });
WriteResult({ "nInserted" : 1 })

> db.obj.findOne()
{
        "_id" : ObjectId("55029b16773fc1f962baf146"),
        "name" : "obj1",
        "arr" : [
                {
                        "elemName" : "elem1",
                        "elemValue" : 1
                },
                {
                        "elemName" : "elem2",
                        "elemValue" : 2
                }
        ],
        "subObj" : {
                "subName" : "subName1",
                "subArr" : [
                        "subElem1",
                        "subElem2",
                        "subElem3"
                ]
        }
}

以陣列形式,插入多行
var objs = [
  {
    name: "obj2",
    arr: [{elemName: "elem1", elemValue: 1}, {elemName: "elem2", elemValue: 2}],
    subObj: {
        subName: "subName2",
        subArr: ["subElem1", "subElem2", "subElem3"]
      }
  },
  {
    name: "obj3",
    arr: [{elemName: "elem1", elemValue: 1}, {elemName: "elem2", elemValue: 2}],
    subObj: {
        subName: "subName3",
        subArr: ["subElem1", "subElem2", "subElem3"]
      }
  }
];

> db.obj.insert(objs);
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})


bulk方式批次插入
> var bulk = db.obj.initializeUnorderedBulkOp();
> bulk.insert(
...    {
...     name: "bulkObj1",
...     arr: [{elemName: "bulkElemName1", elemValue: 100}, {elemName: "bulkElemName2", elemValue: 200}],
...     subObj: {
...         subName: "bulkSubObj1",
...         subArr: ["bulkSubElem1", "bulkSubElem2", "bulkSubElem3"]
...       }
...   }
... );
> bulk.insert(
...    {
...     name: "bulkObj2",
...     arr: [{elemName: "elem1", elemValue: 1}, {elemName: "elem2", elemValue: 2}],
...     subObj: {
...         subName: "bulkSubObj2",
...         subArr: ["bulkSubElem1", "bulkSubElem2", "bulkSubElem3"]
...       }
...   }
... );

> bulk.execute();
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})











來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/26239116/viewspace-1485423/,如需轉載,請註明出處,否則將追究法律責任。

相關文章