Node.js 使用mongodb 增删改查

re.:
https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/#db.collection.insertOne

/**
 * Created by nick on 2018/1/23.
 */
const dbName = 'test';
const url = 'mongodb://admin:admin123@172.16.34.14:27017/test'; //# 数据库为 test
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
// Use connect method to connect to the server
MongoClient.connect(url, function (err, db) {
    if (err) {
        throw err;
    }
    console.log("Connected successfully to server");
    insertDocuments(db.db(dbName), function () {
        db.close();
    });
});

MongoClient.connect(url, function (err, db) {
    if (err) {
        throw err;
    }
    console.log("Connected successfully to server");
    findDocuments(db.db(dbName), function () {
        db.close();
    });
});

MongoClient.connect(url, function (err, db) {
    if (err) {
        throw err;
    }
    console.log("Connected successfully to server");
    updateDocument(db.db(dbName), function () {
        db.close();
    });
});

MongoClient.connect(url, function (err, db) {
    if (err) {
        throw err;
    }
    console.log("Connected successfully to server");
    removeDocument(db.db(dbName), function () {
        db.close();
    });
});

MongoClient.connect(url, function (err, db) {
    if (err) {
        throw err;
    }
    console.log("Connected successfully to server");
    indexCollection(db.db(dbName), function () {
        db.close();
    });
});

var insertDocuments = function (db, callback) {
    // Get the documents collection
    var collection = db.collection('documents');
    // Insert some documents
    collection.insertMany([
        { a : 1 }, { a : 2 }, { a : 3 }
    ], function (err, result) {
        assert.equal(err, null);
        assert.equal(3, result.result.n);
        assert.equal(3, result.ops.length);
        console.log("Inserted 3 documents into the collection");
        callback(result);
    });
}
var findDocuments = function (db, callback) {
    // Get the documents collection
    var collection = db.collection('documents');
    // Find some documents
    collection.find({}).toArray(function (err, docs) {
        assert.equal(err, null);
        console.log("Found the following records");
        console.log(docs)
        callback(docs);
    });
}

var findDocuments = function (db, callback) {
    // Get the documents collection
    var collection = db.collection('documents');
    // Find some documents
    collection.find({ 'a' : 3 }).toArray(function (err, docs) {
        assert.equal(err, null);
        console.log("Found the following records");
        console.log(docs);
        callback(docs);
    });
}

var updateDocument = function (db, callback) {
    // Get the documents collection
    var collection = db.collection('documents');
    // Update document where a is 2, set b equal to 1
    collection.updateOne({ a : 2 }
        , { $set : { b : 1 } }, function (err, result) {
            assert.equal(err, null);
            assert.equal(1, result.result.n);
            console.log("Updated the document with the field a equal to 2");
            callback(result);
        });
}

var removeDocument = function (db, callback) {
    // Get the documents collection
    var collection = db.collection('documents');
    // Delete document where a is 3
    collection.deleteOne({ a : 3 }, function (err, result) {
        assert.equal(err, null);
        assert.equal(1, result.result.n);
        console.log("Removed the document with the field a equal to 3");
        callback(result);
    });
}

var indexCollection = function (db, callback) {
    db.collection('documents').createIndex(
        { "a" : 1 },
        null,
        function (err, results) {
            console.log(results);
            callback();
        }
    );
};

  





basic use:

var cursor = db.collection('inventory').find({ 
  status: "A", 
  qty: { $lt: 30 }
});
<=>
SELECT * FROM inventory WHERE status = "A" AND qty < 30


---
var cursor = db.collection('inventory').find({ 
  $or: [ {status: "A" }, { qty: { $lt: 30 } } ]
});
<=>
SELECT * FROM inventory WHERE status = "A" OR qty < 30


---
var cursor = db.collection('inventory').find({ 
  status: "A",
  $or: [ { qty: { $lt: 30 } }, { item: { $regex: "^p" } } ]
});
<=>
SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")


---
var cursor = db.collection('inventory').find({ 
  size: { w: 21, h: 14, uom: "cm" }
});
var cursor = db.collection('inventory').find({ 
  "size.uom": "in"
});
var cursor = db.collection('inventory').find({ 
  "size.h": { $lt: 15 }, 
  "size.uom": "in", 
  status: "D"
});


---
Query an Array
https://docs.mongodb.com/manual/tutorial/query-arrays/

- Match an Array
The following example queries for all documents where the field tags value is an array 
with exactly two elements, "red" and "blank", in the specified order:
//TODO tags数组是[ "red", "blank" ]的精确查找(值和顺序是一致的)
var cursor = db.collection('inventory').find({ 
  tags: [ "red", "blank" ]
});

If, instead, you wish to find an array that contains both the elements `"red"` and 
`"blank"`, without regard to order or other elements in the array, use the [`$all`]
(https://docs.mongodb.com/manual/reference/operator/query/all/#op._S_all "$all") operator:
//TODO tags数组内包含“red”和“blank”,不管顺序和其他元素
var cursor = db.collection('inventory').find({ 
  tags: { $all: [ "red", "blank" ]}
});


- Query an Array for an Element
The following example queries for all documents where tags is an array that contains the 
string "red" as one of its elements:
//TODO tags数组中包含元素“red”
var cursor = db.collection('inventory').find({ 
  tags: "red"
});

For example, the following operation queries for all documents where the array dim_cm 
contains at least one element whose value is greater than 25.
//TODO dim_cm数组中至少有一个元素大于25
var cursor = db.collection('inventory').find({ 
  dim_cm: { $gt: 25 }
});


- Specify Multiple Conditions for Array Elements
The following example queries for documents where the dim_cm array contains elements 
that in some combination satisfy the query conditions; e.g., one element can satisfy the 
greater than 15 condition and another element can satisfy the less than 20 condition, or a
 single element can satisfy both:
//TODO dim_cm数组中有的元素大于15,有的元素小于20,或者有的元素大于15小于20
var cursor = db.collection('inventory').find({ 
  dim_cm: { $gt: 15, $lt: 20 }
});

Query for an Array Element that Meets Multiple Criteria
查询符合多个标准的数组元素
The following example queries for documents where the `dim_cm` array contains at least 
one element that is both greater than 
([`$gt`](https://docs.mongodb.com/manual/reference/operator/query/gt/#op._S_gt "$gt"))
 `22` and less than
 ([`$lt`](https://docs.mongodb.com/manual/reference/operator/query/lt/#op._S_lt "$lt")) `30`:
//TODO dim_cm数组中有的元素既大于22又小于30
var cursor = db.collection('inventory').find({ 
  dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } }
});


- Query for an Element by the Array Index Position
The following example queries for all documents where the second element in the array 
dim_cm is greater than 25:
//TODO dim_cm数组中第二个元素大于25
var cursor = db.collection('inventory').find({ 
  "dim_cm.1": { $gt: 25 }
});


- Query an Array by Array Length
For example, the following selects documents where the array tags has 3 elements.
var cursor = db.collection('inventory').find({ 
  tags: { $size: 3 }
});


- Query an Array of Embedded Documents

[{ item: "journal",
    instock: [
      { warehouse: "A", qty: 5 },
      { warehouse: "C", qty: 15 }]},]

- Query for a Document Nested in an Array
The following example selects all documents where an element in the instock array 
matches the specified document:

var cursor = db.collection('inventory').find({ 
  instock: { warehouse: "A", qty: 5 }
});

//TODO 元素的顺序很重要
the following query does not match any documents in the inventory collection:
//TODO 以下找不到任何数据
var cursor = db.collection('inventory').find({ 
  instock: { qty: 5, warehouse: "A" }
});


- Specify a Query Condition on a Field Embedded in an Array of Documents
The following example selects all documents where the instock array has at least one 
embedded document that contains the field qty whose value is less than or equal to 20:
//TODO instock数组中,任意元素的qty字段的值小于等于20
var cursor = db.collection('inventory').find({ 
  "instock.qty": { $lte: 20 }
});


- Use the Array Index to Query for a Field in the Embedded Document
The following example selects all documents where the instock array has as its first 
element a document that contains the field qty whose value is less than or equal to 20:
//TODO instock数组中,第一个元素的qty字段小于等于20
var cursor = db.collection('inventory').find({ 
  "instock.0.qty": { $lte: 20 }
});


- Specify Multiple Conditions for Array of Documents

- A Single Nested Document Meets Multiple Query Conditions on Nested Fields
The following example queries for documents where the instock array has at least one 
embedded document that contains both the field qty equal to 5 and the field warehouse 
equal to A:
/*
TODO instock数组中,至少有一个元素满足qty字段的值为5,warehouse字段的值为“A”,
和字段的顺序无关
*/
var cursor = db.collection('inventory').find({ 
  instock: { $elemMatch: { qty: 5, warehouse: "A" } }
});

The following example queries for documents where the instock array has at least one 
embedded document that contains the field qty that is greater than 10 and less than or 
equal to 20:
//TODO instock数组中,至少有一个元素的qty字段的值大于10且小于等于20
var cursor = db.collection('inventory').find({ 
  instock: { $elemMatch: { qty: { $gt: 10, $lte: 20 } } }
});


- Combination of Elements Satisfies the Criteria
元素组合满足标准
For example, the following query matches documents where any document nested in the 
instock array has the qty field greater than 10 and any document (but not necessarily the 
same embedded document) in the array has the qty field less than or equal to 20:
//TODO instock数组中,有的元素的qty字段的值大于10,有的元素的qty字段的值小于等于20
var cursor = db.collection('inventory').find({ 
  "instock.qty": { $gt: 10, $lte: 20 }
});

The following example queries for documents where the instock array has at least one 
embedded document that contains the field qty equal to 5 and at least one embedded 
document (but not necessarily the same embedded document) that contains the field 
warehouse equal to A:
//TODO instock数组中,有的元素的qty字段的值为5,有的元素的warehouse字段的值为“A"
var cursor = db.collection('inventory').find({ 
  "instock.qty": 5, "instock.warehouse": "A"
});


---
- Project Fields to Return from Query
[
{ item: "journal",
    status: "A",
    size: { h: 14, w: 21, uom: "cm" },
    instock: [ { warehouse: "A", qty: 5 } ]},
]


- Return All Fields in Matching Documents
var cursor = db.collection('inventory').find({ 
  status: "A"
});
<=>
SELECT * from inventory WHERE status = "A"


---
- Return the Specified Fields and the _id Field Only
var cursor = db.collection('inventory').find({ 
  status: "A"
}).project({ item: 1, status: 1 });
<=>
SELECT _id, item, status from inventory WHERE status = "A"


- Suppress _id Field
var cursor = db.collection('inventory').find({ 
  status: "A"
}).project({ item: 1, status: 1, _id: 0 });
<=>
SELECT item, status from inventory WHERE status = "A"


---
- Return All But the Excluded Fields
var cursor = db.collection('inventory').find({ 
  status: "A"
}).project({ status: 0, instock: 0 });


---
- Return Specific Fields in Embedded Documents
var cursor = db.collection('inventory').find({ 
  status: "A"
}).project({ item: 1, status: 1, "size.uom": 1 });


---
- Suppress Specific Fields in Embedded Documents
var cursor = db.collection('inventory').find({ 
  status: "A"
}).project({ "size.uom": 0 });


---
- Projection on Embedded Documents in an Array
var cursor = db.collection('inventory').find({ 
  status: "A"
}).project({ item: 1, status: 1, "instock.qty": 1 });


---
- Project Specific Array Elements in the Returned Array
The following example uses the [`$slice`](https://docs.mongodb.com/manual/reference
/operator/projection/slice/#proj._S_slice "$slice") projection operator to return the last 
element in the `instock` array:
//TODO inventory集合中,status值为”A“,返回值包含字段item,status,instock,其中instock数组中只返回最后一项元素($slice:-2 最后两项元素,$slice:2 前两项元素)。
var cursor = db.collection('inventory').find({ 
  status: "A"
}).project({ item: 1, status: 1, "instock": { $slice: -1 } });


db.students.find( { grades: { $elemMatch: {
                                            mean: { $gt: 70 },
                                            grade: { $gt:90 }
                                          } } },
                  { "grades.$": 1 } )


 In the following query, the projection { "grades.$": 1 } returns only the first element with the mean greater than 70 for the grades field:
db.students.find(
   { "grades.mean": { $gt: 70 } },
   { "grades.$": 1 }
)

{ "_id" : 7, "grades" : [  {  "grade" : 80,  "mean" : 75,  "std" : 8 } ] }
{ "_id" : 8, "grades" : [  {  "grade" : 92,  "mean" : 88,  "std" : 8 } ] }


---
- Update Documents in a Collection
[
{ item: "canvas",
    qty: 100,
    size: {h: 28, w: 35.5, uom: "cm"},
    status: "A"},
]

uses the [`$currentDate`](https://docs.mongodb.com/manual/reference/operator/update
/currentDate/#up._S_currentDate "$currentDate") operator to update the value of the 
`lastModified` field to the current date. If `lastModified` field does not exist, 
[`$currentDate`](https://docs.mongodb.com/manual/reference/operator/update
/currentDate/#up._S_currentDate "$currentDate") will create the field. See 
[`$currentDate`](https://docs.mongodb.com/manual/reference/operator/update
/currentDate/#up._S_currentDate "$currentDate") for details.


- Update a Single Document

db.collection('inventory').updateOne(
  { item: "paper" },
  { $set: { "size.uom": "cm", status: "P" },
    $currentDate: { lastModified: true } })
.then(function(result) {
  // process result
})            


- Update Multiple Documents

db.collection('inventory').updateMany(
  { qty: { $lt: 50 } },
  { $set: { "size.uom": "in", status: "P" },
    $currentDate: { lastModified: true } })
.then(function(result) {
  // process result
})            


---
- Replace a Document
The following example replaces the first document from the inventory collection where item: "paper":
//TODO 替换
db.collection('inventory').replaceOne(
  { item: "paper" },
  { item: "paper", 
    instock: [
      { warehouse: "A", qty: 60 },
      { warehouse: "B", qty: 40 }
    ]})
.then(function(result) {
  // process result
})





  • 注意:
Although you can express this query using the [`$or`](https://docs.mongodb.com
/manual/reference/operator/query/or/#op._S_or "$or") operator, choose the [`$in`]
(https://docs.mongodb.com/manual/reference/operator/query/in/#op._S_in "$in") 
operator rather than the [`$or`](https://docs.mongodb.com/manual/reference/operator
/query/or/#op._S_or "$or") operator when performing equality checks on the same field.


---







Additional Methods for Inserts

The following methods can also add new documents to a collection:


  • Project Specific Array Elements in the Returned Array
    $elemMatch, $slice, and $ are the only way to project specific elements to include in the returned array. For instance, you cannot project specific array elements using the array index; e.g. { "instock.0": 1 } projection will not project the array with the first element.

    • table join => $lookup

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/#examples

https://docs.mongodb.com/manual/reference/operator/query/expr/#op._S_expr


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,335评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,895评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,766评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,918评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,042评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,169评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,219评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,976评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,393评论 1 304
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,711评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,876评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,562评论 4 336
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,193评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,903评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,142评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,699评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,764评论 2 351

推荐阅读更多精彩内容