nodejs连接MongoDB及增删查改操作
2019-07-31 本文已影响0人
落花夕拾
//客户端
const MongoClient = require('mongodb').MongoClient;
//链接url
const url = 'mongodb://localhost:27017';
//数据库名
const dbName = 'test1'
//创建客户端
const client = new MongoClient(url, {useNewUrlParser:true});
//连接数据库
(async function() {
await client.connect();
console.log('连接成功');
//获取数据库
const db = client.db(dbName);
//获取集合
const fruitsCol = db.collection('fruits');
/*
插入: insertOne /insertMany
*/
//插入单条数据
let r = await fruitsCol.insertOne(
{name:'芒果',price:21}
)
//插入多条数据
await fruitsCol.insertMany(
[{name:'菠萝蜜',price:122},
{name:'西瓜',price:6.98},
{name:'百香果',price:24.5,address:'广西省'}
]
)
/*
* 查詢find({}).toArray
* */
//查询数据.toArray()方法转换成数据对象
let f = await fruitsCol.find({name:'西瓜'}).toArray();
console.log(f)
//聚合操作(重点) (https://www.runoob.com/mongodb/mongodb-aggregate.html)
f = await fruitsCol.aggregate(
[
{$match: { name:'菠萝蜜' }},
{$group:{_id:'$name', sum:{$sum:'$price'}}},
{$group:{_id:'$name', avg:{$avg:'$price'}}},
]
)
.toArray();
console.log(f)
// db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])
f = await fruitsCol.aggregate(
[
{$match:{name:'百香果'}},
{$group:{_id:'$name',address:{$push:'$address'}}}
]
)
.toArray();
console.log(f)
f = await fruitsCol.find({address:'广西省'}).toArray();
console.log(f);
/*
* 更新操作 update({})
* db.mycol.update([{})
* collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
* */
// db.col.updateOne({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}})
f = await fruitsCol.updateMany(
{name:'百香果'},
{$set:{name:'荔枝'}}
);
console.log("更新成功", f.result);
console.log("更新成功", r.result);
f = await fruitsCol.find({name:'荔枝'}).toArray();
console.log(f)
f = await fruitsCol.updateOne(
{
address:'广西省'
},
{$set:{address:'江西省'}})
console.log(f.result);
/*
* 删除操作
* db.mycol.update([{})
* */
f = await fruitsCol.deleteOne(
{address:'江西省'}
)
console.log('删除成功',f.result)
f = await fruitsCol.deleteMany({address:'广西省'})
console.log('delete success...' ,f.result);
//输入文档
})()
1、连接

2、查询

3、更新

4、删除

5、在robo3t中查看
