mongodb 3.x以上版本与mongodb 2.x版本语法区别

时间:2021-12-26 20:06:17

2.x

const MongoClient = require(‘mongodb‘).MongoClient;
const url = ‘mongodb://localhost:27017/test‘;
MongoClient.connect(url, function (err, db) {
if (err) throw new Error(err);
db.collection(‘myCollection‘).updateOne({ // Update method ‘updateOne‘
greetings: "Hellu" },
{ $set: { greetings: "Whut?" }},
function (err, result) {
if (err) throw new Error(err);
db.close(); // Don‘t forget to close the connection when you are done
});
});

3.x

const MongoClient = require(‘mongodb‘).MongoClient;

const url = ‘mongodb://localhost:27017/wang‘;

MongoClient.connect(url, function(err, client) {
    if(err) throw new Error(err);
    var db = client.db(‘wang‘);
    db.collection(‘myCollection‘).updateOne({ // Update method ‘updateOne‘
    greetings: "Hellu" },{ $set: {greetings: "Whut?"}},
                        function(err,result) {
                        if(err) throw new Error(err);
                        client.close(); // Don‘t forget to close the connection when you are done
                        });
});