怎么连接mongodb数据库
mongodb数据库创建后,需使用内网进行访问,暂不支持外网访问。
Shell连接mongodb数据库示例
典型的连接命令如下:
[root@mtyun ~]# mongo 172.16.185.3
MongoDB shell version: 3.4.4
connecting to: 172.16.185.3/test
replset:PRIMARY> use admin
switched to db admin
replset:PRIMARY>db.auth("root","root123!")
1
replset:PRIMARY>show dbs
admin 0.000GB
local 0.000GB
replset:PRIMARY>
Python连接mongodb数据库示例
安装pythonmongo包
pip install pymongo
示例代码
新增
# Python3
import random
import datetime
from pymongo import MongoClient
mongodb_connect_url = 'mongodb://username:yourpassword@your_ip_address/admin'
client = MongoClient(mongodb_connect_url)
db = client.test_database
db.posts.drop()
posts = []
for i in range(5):
posts.append({"author": random.choice(["Mike", "Ruby", "Jake"]),
"text": "My first blog post!",
"tags": random.choice(["mongodb", "python", "pymongo"]),
"date": datetime.datetime.utcnow()})
inserted_records = db.posts.insert_many(posts)
print(inserted_records.inserted_ids)
输出:
[ObjectId('59140533fa2a721daa3769e3'), ObjectId('59140533fa2a721daa3769e4'), ObjectId('59140533fa2a721daa3769e5'), ObjectId('59140533fa2a721daa3769e6'), ObjectId('59140533fa2a721daa3769e7')]
查询
from pymongo import MongoClient
import datetime
import random
mongodb_connect_url = 'mongodb://username:yourpassword@your_ip_address/admin'
client = MongoClient(mongodb_connect_url)
db = client.test_database
records = db.posts.find()
for record in records:
print(record)
输出:
{'_id': ObjectId('59140533fa2a721daa3769e3'), 'author': 'Mike', 'text': 'My first blog post!', 'tags': 'python', 'date': datetime.datetime(2017, 5, 11, 6, 31, 15, 569000)}
{'_id': ObjectId('59140533fa2a721daa3769e4'), 'author': 'Jake', 'text': 'My first blog post!', 'tags': 'mongodb', 'date': datetime.datetime(2017, 5, 11, 6, 31, 15, 569000)}
{'_id': ObjectId('59140533fa2a721daa3769e5'), 'author': 'Jake', 'text': 'My first blog post!', 'tags': 'python', 'date': datetime.datetime(2017, 5, 11, 6, 31, 15, 569000)}
{'_id': ObjectId('59140533fa2a721daa3769e6'), 'author': 'Ruby', 'text': 'My first blog post!', 'tags': 'python', 'date': datetime.datetime(2017, 5, 11, 6, 31, 15, 569000)}
{'_id': ObjectId('59140533fa2a721daa3769e7'), 'author': 'Jake', 'text': 'My first blog post!', 'tags': 'pymongo', 'date': datetime.datetime(2017, 5, 11, 6, 31, 15, 569000)}
删除
from pymongo import MongoClient
import datetime
import random
mongodb_connect_url = 'mongodb://username:yourpassword@your_ip_address/admin'
client = MongoClient(mongodb_connect_url)
db = client.test_database
delete_result = db.posts.delete_many({'author':'Jake'})
print("Delete count: ", delete_result.deleted_count)
records = db.posts.find()
for record in records:
print(record)
输出:
Delete count: 3
{'_id': ObjectId('59140533fa2a721daa3769e3'), 'author': 'Mike', 'text': 'My first blog post!', 'tags': 'python', 'date': datetime.datetime(2017, 5, 11, 6, 31, 15, 569000)}
{'_id': ObjectId('59140533fa2a721daa3769e6'), 'author': 'Ruby', 'text': 'My first blog post!', 'tags': 'python', 'date': datetime.datetime(2017, 5, 11, 6, 31, 15, 569000)}
修改
from pymongo import MongoClient
import datetime
import random
mongodb_connect_url = 'mongodb://username:yourpassword@your_ip_address/admin'
client = MongoClient(mongodb_connect_url)
db = client.test_database
new_post = {'author': 'Ruby',
'text': 'My Second blog post!',
'tags': 'Mongodb',
'date': datetime.datetime.utcnow()}
update_result = db.posts.update({"author": "Mike"}, {"$set": new_post}, upsert=False)
for record in db.posts.find():
print(record)
输出:
{'_id': ObjectId('59140533fa2a721daa3769e3'), 'author': 'Ruby', 'text': 'My Second blog post!', 'tags': 'Mongodb', 'date': datetime.datetime(2017, 5, 11, 6, 38, 14, 500000)}
{'_id': ObjectId('59140533fa2a721daa3769e6'), 'author': 'Ruby', 'text': 'My first blog post!', 'tags': 'python', 'date': datetime.datetime(2017, 5, 11, 6, 31, 15, 569000)}
Java连接mongodb数据库示例
示例代码
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
public class App {
public static void main(String[] args) {
try {
/**** 连接到mongodb ****/
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient("mongodb://username:yourpassword@your_ip_address/admin");
/**** 获取testdb ****/
DB db = mongo.getDB("testdb");
/**** 获取user集合 ****/
DBCollection table = db.getCollection("user");
/**** 插入数据 ****/
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
document.put("createdDate", new Date());
table.insert(document);
/**** 搜索 ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
/**** 更新 ****/
BasicDBObject query = new BasicDBObject();
query.put("name", "mkyong");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "mkyong-updated");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
BasicDBObject searchQuery2
= new BasicDBObject().append("name", "mkyong-updated");
DBCursor cursor2 = table.find(searchQuery2);
while (cursor2.hasNext()) {
System.out.println(cursor2.next());
}
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
输出:
{ "_id" : { "$oid" : "51398e6e30044a944cc23e2e"} , "name" : "mkyong" , "age" : 30 , "createdDate" : { "$date" : "2013-03-08T07:08:30.168Z"}}
{ "_id" : { "$oid" : "51398e6e30044a944cc23e2e"} , "age" : 30 , "createdDate" : { "$date" : "2013-03-08T07:08:30.168Z"} , "name" : "mkyong-updated"}
Done
PHP连接mongodb数据库示例
示例代码
comedy;
// 选取集合
$collection = $db->cartoons;
// 添加一条记录
$document = array( "title"=> "Calvin and Hobbes", "author"=> "Bill Watterson" );
$collection->insert($document);
// 再添加一条记录
$document = array( "title" => "XKCD", "online" => true );
$collection->insert($document);
// 查找所有记录
$cursor = $collection->find();
// 打印
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}
?>
输出:
Calvin and Hobbes
XKCD
发表评论