Mongodb

安装

安装brew

安装mongodb

brew install mongodb

创建目录 ~/data/db

mongod --dbpath=./data/db  

安装可视化管理工具 Robomongo

create->connection->name: myDatabase-> save

使用

shell

~ mongo
\> use myDatabase
\> db.pd_info.find({})
…...

nodejs
到项目目录下

npm install --save mongodb

创建js文件db_server.js

update 2018.05.25

const MongoClient = require('mongodb').MongoClient
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017/myDatabase';

// Use connect method to connect to the server
MongoClient.connect(url, (err, client) => {
    assert.equal(null, err);
    console.log("Connected successfully to server");
    const db = client.db('table_name');
    const col = db.collection('collection_name');

    client.close();
});
node db_server.js

操作

插入数据

col.insertOne({"name": "test"}, (err, res) => {
  console.log("成功");
  client.close();
})

插入多条使用insertMany

查询数据

col.find({"name": "test"}).toArray((err, result) => {
  console.log(result);
  client.close();
})

更新数据

col.updateOne({
  "name": "test"
}, {
  $set: {
    "url": "test"
  }
}, (err, res) => {
    client.close();
})

更新多条用updateMany

删除数据

col.deleteOne({"name": "test"}, (err, obj) => {
  client.close();
})

删除多条用deleteMany

排序

col
  .find()
  .sort({
    type: 1 // 1升序 -1降序
  })
  .toArray(...)

数量

col
  .find()
  .limit(2)
  .toArray(...)

指定返回键

col
  .find()
  .project({name: 1})
  .toArray(...)

删除集合

col.drop((err, delOk) => {  //  delOk 成功true失败false
    client.close();
})

联合查找

db.getCollection('pd_info').aggregate([
    { 
        $match: {
            proname: /玉米/
        }
    },
    { //用集合pd_info数据中的cid去gc_company集合中找,返回的放到cominfo中
        $lookup: {  
            from: 'gc_company',  
            localField: 'cid', 
            foreignField: 'cid', 
            as: 'cominfo' 
        } 
    },
    { 
        $limit: 10 
    },
    { 
        $project: { 
            proname: 1, 
            cid: 1, 
            'cominfo.comname': 1 
        } 
    } 
]);

文档

正则查找数字

If you are wanting to do a pattern match on numbers, the way to do it in mongo is use the $where expression and pass in a pattern match.

> db.test.find({ $where: "/^123.*/.test(this.example)" })
{ "_id" : ObjectId("4bfc3187fec861325f34b132"), "example" : 1234 }
Comments
Write a Comment