//客户端
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、连接
![](https://img.haomeiwen.com/i3287016/4e15b2093f068a6a.png)
1.png
2、查询
![](https://img.haomeiwen.com/i3287016/64f56a7be31e965f.png)
2.png
3、更新
![](https://img.haomeiwen.com/i3287016/f7b7d2feb6e4f53b.png)
3.png
4、删除
![](https://img.haomeiwen.com/i3287016/23288f4f48cd4d38.png)
4.png
5、在robo3t中查看
![](https://img.haomeiwen.com/i3287016/40607c17ee957726.png)
robo3.png
网友评论