Node.js|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 Documentdb.collection('inventory').updateOne( { item: "paper" }, { $set: { "size.uom": "cm", status: "P" }, $currentDate: { lastModified: true } }) .then(function(result) { // process result })- Update Multiple Documentsdb.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:
  • db.collection.update() when used with the upsert: true option.
  • db.collection.updateOne() when used with the upsert: true option.
  • db.collection.updateMany() when used with the upsert: true option.
  • db.collection.findAndModify() when used with the upsert: true option.
  • db.collection.findOneAndUpdate() when used with the upsert: true option.
  • db.collection.findOneAndReplace() when used with the upsert: true option.
  • db.collection.save().
  • db.collection.bulkWrite().
  • 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
【Node.js|Node.js 使用mongodb 增删改查】https://docs.mongodb.com/manual/reference/operator/query/expr/#op._S_expr
  • sql => mongo对比
    https://docs.mongodb.com/manual/reference/sql-comparison/

    推荐阅读