mongodb

MongDB和JSON對象有些相似。mongodb

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

Query with the mongo shellshell

使用數據庫數據庫

use

建立數據庫(insert會同時建立myNewDB和myNewCollection)ui

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

建立集合rest

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

建立viewcode

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安裝地址ip

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()
相關文章
相關標籤/搜索