mongodb

MongDB和JSON对象有些类似。

{
    name: "sue",
    age: 26,
    status: "A",
    groups: ["news", sports]
}

Query with the mongo shell

使用数据库

use

创建数据库(insert会同时创建myNewDB和myNewCollection)

use myNewDB 
DB.myNewCollection1.insert({x: 1})

创建集合

db.myNewCollection2.insert( { x: 1 } )
db.myNewCollection3.createIndex( { y: 1 } )

创建view

db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline> } )
db.runCommand( { create: <view>, viewOn: <source>, pipeline: <pipeline>, collation: <collation> } )

删除view

db.collection.drop() 

mongo Shell

mongo Shell是一种与MongoDb进行互动的JavaScript接口。可以使用mongo shell去查询和更新数据。
在使用mongo shell 前确认mongoBb正在运行。

1.进入mongodb安装地址

cd <mongodb installation dir>

2.启动mongo,当运行mongo不带任何参数,默认运行localhost:27017

./bin/mongo

显示正在使用的数据库

db

显示可使用的数据库

show dbs
或者db.getSiblingDB()

插入document

db.restaurants.insert(
   {
      "address" : {
         "street" : "2 Avenue",
         "zipcode" : "10075",
         "building" : "1480",
         "coord" : [ -73.9557413, 40.7720266 ]
      },
      "borough" : "Manhattan",
      "cuisine" : "Italian",
      "grades" : [
         {
            "date" : ISODate("2014-10-01T00:00:00Z"),
            "grade" : "A",
            "score" : 11
         },
         {
            "date" : ISODate("2014-01-16T00:00:00Z"),
            "grade" : "B",
            "score" : 17
         }
      ],
      "name" : "Vella",
      "restaurant_id" : "41704620"
   }
)

查询集合中所有的documents

db.restaurants.find()

查询(按条件查询)

db.restaurants.find( { "borough": "Manhattan" } )
db.restaurants.find( { "address.zipcode": "10075" } )

大于小于

db.restaurants.find( { "grades.score": { $gt: 30 } } )
db.restaurants.find( { "grades.score": { $lt: 10 } } )

逻辑与

db.restaurants.find( { "cuisine": "Italian", "address.zipcode": "10075" } )

逻辑或

db.restaurants.find(
   { $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ] }
)

排序

db.restaurants.find().sort( { "borough": 1, "address.zipcode": 1 } )

Update data with the mongo shell

db.restaurants.update(
    { "name" : "Juni" },
    {
      $set: { "cuisine": "American (New)" },
      $currentDate: { "lastModified": true }
    }
)
db.restaurants.update(
  { "restaurant_id" : "41156888" },
  { $set: { "address.street": "East 31st Street" } }
)
//批量更新
db.restaurants.update(
  { "address.zipcode": "10016", cuisine: "Other" },
  {
    $set: { cuisine: "Category To Be Determined" },
    $currentDate: { "lastModified": true }
  },
  { multi: true}
)

remove data with the mongo shell

删除

db.restaurants.remove( { "borough": "Manhattan" } )
//只删除一条
db.restaurants.remove( { "borough": "Queens" }, { justOne: true } )
//删除所有
db.restaurants.remove( { } )
db.restaurants.drop()
    原文作者:sll
    原文地址: https://segmentfault.com/a/1190000008185230
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞