分类:NoSQL     文章(7) 篇

MongoDB无法启动终极解决办法 (2012-02-11)

MongoDB经常遇到无法启动的问题,以下是终极解决办法:
原文地址:http://ubuntuforums.org/archive/index.php/t-1715866.html

Hey guys, I've been a long time lurker but this is my first post! I'm running Ubuntu 10.10 64bit, and I'm a newbie when it comes to networking.

My issue is that there seems to be a socket bound to a port blocking MongoDB from accessing it's usual port 27017. The strange thing that it was working just fine until recently and I can't figure out what I did to screw things up... I can make it use a different port but the reason why it can't bind to the default port and why I can't fix it is really bothering me. I've tried rebooting the machine even with nothing else running when I try to run Mongo is still blocked giving the following message:
ropes@ropes:~/mongodb-linux-x86_64-1.8.0/bin$ ./mongod
./mongod --help for help and startup options
Sun Mar 27 14:08:14 [initandlisten] MongoDB starting : pid=2718 port=27017 dbpath=/data/db/ 64-bit 
Sun Mar 27 14:08:14 [initandlisten] db version v1.8.0, pdfile version 4.5
Sun Mar 27 14:08:14 [initandlisten] git version: 9c28b1d608df0ed6ebe791f63682370082da41c0
Sun Mar 27 14:08:14 [initandlisten] build sys info: Linux bs-linux64.10gen.cc 2.6.21.7-2.ec2.v1.2.fc8xen #1 SMP Fri Nov 20 17:48:28 EST 2009 x86_64 BOOST_LIB_VERSION=1_41
Sun Mar 27 14:08:14 [initandlisten] waiting for connections on port 27017
Sun Mar 27 14:08:14 [initandlisten] listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:27017
Sun Mar 27 14:08:14 [websvr] web admin interface listening on port 28017
Sun Mar 27 14:08:14 [initandlisten] addr already in use
Sun Mar 27 14:08:14 [initandlisten] now exiting
Sun Mar 27 14:08:14 dbexit: 
Sun Mar 27 14:08:14 [initandlisten] shutdown: going to close listening sockets...
Sun Mar 27 14:08:14 [websvr] listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:28017
Sun Mar 27 14:08:14 [initandlisten] shutdown: going to flush diaglog...
Sun Mar 27 14:08:14 [websvr] addr already in use
Sun Mar 27 14:08:14 [initandlisten] shutdown: going to close sockets...
Sun Mar 27 14:08:14 [initandlisten] shutdown: waiting for fs preallocator...
Sun Mar 27 14:08:14 [initandlisten] shutdown: closing all files...
Sun Mar 27 14:08:14 closeAllFiles() finished
Sun Mar 27 14:08:14 [initandlisten] shutdown: removing fs lock...
Sun Mar 27 14:08:14 dbexit: really exiting nowSo I tried running netstat to check the port process to kill...
ropes@ropes:~$ netstat -lnptu
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:28017 0.0.0.0:* LISTEN - 
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN - 
tcp 0 0 127.0.0.1:27017 0.0.0.0:* LISTEN - 
tcp6 0 0 ::1:631 :::* LISTEN - 
udp 0 0 0.0.0.0:68 0.0.0.0:* - 
udp 0 0 0.0.0.0:41548 0.0.0.0:* - 
udp 0 0 0.0.0.0:5353 0.0.0.0:* - 
udp6 0 0 :::36250 :::* - 
udp6 0 0 :::5353 :::* - 
Do I have some weird setting that's blocking the association of port bindings to the PID?
so sockstat..
ropes@ropes:~$ sockstat -p 27017
USER PROCESS PID PROTO SOURCE ADDRESS FOREIGN ADDRESS STATEI'm really confused, it seems like the socket isn't bound at all but Mongo still can't bind to the port, so there's some type of ghost binding?

I've pretty much been following this blog about tracking down port issues:
http://www.techrepublic.com/blog/security/list-open-ports-and-listening-services/443

but whatever is causing this issue is beyond my knowledge base.
Thanks for any help you guys can give!

解决方法

Hey you probably found a solution already, but in case anyone else wants a quick fix here's a solution to find and kill the Mongo server.

Get the process list:
ps -eF | grep 'mongo\|PID'This will return the PIDs which can then be used to kill the process and hopefully close the sockets as well.
UID PID PPID C SZ RSS PSR STIME TTY TIME CMD
mongodb 1260 1 0 26316 4316 4 Mar29 ? 00:00:00 /usr/lib/mongodb/mongod --config /etc/mongodb.conf
ropes 19931 18808 0 2239 864 1 03:16 pts/2 00:00:00 grep --color=auto mongo\|PIDProblem solved..

awesome, thanks! i'm able to launch it now. you rock!

点击查看原文阅读(63) | 评论(0) | 分类:NoSQL

MongoDB的PHP查询操作语法 (2011-12-11)

最近经常忘了查询语法,这里总结PHP操作MongoDB查询语法:

一、准备查询条件
// 字段字串为
$querys = array("name"=>"shian");
 
// 数值等于多少
$querys = array("number"=>7);
 
// 数值大于多少
$querys = array("number"=>array('$gt' => 5));
 
// 数值大于等于多少
$querys = array("number"=>array('$gte' => 2));
 
// 数值小于多少
$querys = array("number"=>array('$lt' => 5));
 
// 数值小于等于多少
$querys = array("number"=>array('$lte' => 2));
 
// 数值介于多少
$querys = array("number"=>array('$gt' => 1,'$lt' => 9));
 
// 数值不等于某值
$querys = array("number"=>array('$ne' => 9));
 
// 使用js下查询条件
$js = "function(){
    return this.number == 2 && this.name == 'shian';
}";
$querys = array('$where'=>$js);
 
// 字段等于哪些值
$querys = array("number"=>array('$in' => array(1,2,9)));
 
// 字段不等于哪些值
$querys = array("number"=>array('$nin' => array(1,2,9)));
 
// 使用正则查询
$querys = array("name" => new MongoRegex("/shi/$i"));
 
// 或
$querys = array('$or' => array(array('number'=>2),array('number'=>9)));
 
 
 二、需要得到哪些字段
// 需要列出哪些字段(空为全部)
$fields = array();
 三、执行查询
// find: 列出查询到所有资料
$find_data = iterator_to_array($user->find($querys,$fields));
print_r($find_data);
 
// findOne: 只列出第一节点资料
$findone_data = $user->findOne($querys,$fields);
print_r($findone_data);

 

点击查看原文阅读(271) | 评论(1) | 分类:NoSQL

Node+Mongoose常用查询中文文档 (2011-12-04)

 Mongoose 模型提供了 find, findOne, 和 findById 方法用于文档查询。

Model.find

Model.find(query, fields, options, callback)
// fields 和 options 都是可选参数

简单查询

Model.find({ 'csser.com': 5 }, function (err, docs) { // docs 是查询的结果数组 });

只查询指定键的结果

Model.find({}, ['first', 'last'], function (err, docs) {
  // docs 此时只包含文档的部分键值
})

Model.findOne

与 Model.find 相同,但只返回单个文档

Model.findOne({ age: 5}, function (err, doc){
  // doc 是单个文档
});

Model.findById

与 findOne 相同,但它接收文档的 _id 作为参数,返回单个文档。_id 可以是字符串或 ObjectId 对象。

Model.findById(obj._id, function (err, doc){
  // doc 是单个文档
});

Model.count

返回符合条件的文档数。

Model.count(conditions, callback);

Model.remove

删除符合条件的文档。

Model.remove(conditions, callback);

Model.distinct

查询符合条件的文档并返回根据键分组的结果。

Model.distinct(field, conditions, callback);

Model.where

当查询比较复杂时,用 where:

Model
.where('age').gte(25)
.where('tags').in(['movie', 'music', 'art'])
.select('name', 'age', 'tags')
.skip(20)
.limit(10)
.asc('age')
.slaveOk()
.hint({ age: 1, name: 1 })
.run(callback);

Model.$where

有时我们需要在 mongodb 中使用 javascript 表达式进行查询,这时可以用 find({$where : javascript}) 方式,$where 是一种快捷方式,并支持链式调用查询。

Model.$where('this.firstname === this.lastname').exec(callback)

Model.update

使用 update 子句更新符合指定条件的文档,更新数据在发送到数据库服务器之前会改变模型的类型。

var conditions = { name: 'borne' }
  , update = { $inc: { visits: 1 }}
  , options = { multi: true };

Model.update(conditions, update, options, callback)

注意:为了向后兼容,所有顶级更新键如果不是原子操作命名的,会统一被按 $set 操作处理,例如:

var query = { name: 'borne' };
Model.update(query, { name: 'jason borne' }, options, callback)

// 会被这样发送到数据库服务器

Model.update(query, { $set: { name: 'jason borne' }}, options, callback)

查询 API

如果不提供回调函数,所有这些方法都返回 Query 对象,它们都可以被再次修改(比如增加选项、键等),直到调用 exec 方法。

var query = Model.find({});

query.where('field', 5);
query.limit(5);
query.skip(100);

query.exec(function (err, docs) {
  // called when the `query.complete` or `query.error` are called
  // internally
});

[完]

点击查看原文阅读(188) | 评论(0) | 分类:NoSQL

MongoDB高级查询 (2011-12-02)

详情可以参考官方文档:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D

 Mongodb一些常用的查询

WHERE查询

// i.e., select * from things where x=3 and y="foo"
db.things.find( { x : 3, y : "foo" } );

 

j不等于3,k大于10

db.things.find({j: {$ne: 3}, k: {$gt: 10} });

 

存储数组元素

db.things.insert({colors : ["blue", "black"]})
db.things.insert({colors : ["yellow", "orange", "red"]})
//查询结果
db.things.find({colors : {$ne : "red"}})
{"_id": ObjectId("4dc9acea045bbf04348f9691"), "colors": ["blue","black"]}

 

对比操作符

db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value
db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= 

 

$all 全部属于

db.things.find( { a: { $all: [ 2, 3 ] } } )

 

$exists 字段存在

db.things.find( { a : { $exists : true } } )
db.things.find( { a : { $exists : false } } )
true返回存在字段a的数据,false返回不存在字度a的数据。

 

$mod 取模运算

db.things.find( { a : { $mod : [ 10 , 1 ] } } )
条件相当于a % 10 == 1 即a除以10余数为1的。

 

$ne 不等于

db.things.find( { x : { $ne : 3 } } )
条件相当于x<>3,即x不等于3。

 

$in 属于

db.things.find({j:{$in: [2,4,6]}})
条件相当于j等于[2,4,6]中的任何一个。

 

$nin 不属于

db.things.find({j:{$nin: [2,4,6]}})
条件相当于 j 不等于 [2,4,6] 中的任何一个。

 

$or 或 (注意:MongoDB 1.5.3后版本可用)

db.foo.find( { $or : [ { a : 1 } , { b : 2 } ] } )
符合条件a=1的或者符合条件b=2的数据都会查询出来。

 

$size 数量,尺寸

db.things.find( { a : { $size: 1 } } )
条件相当于a的值的数量是1(a必须是数组,一个值的情况不能算是数量为1的数组)。

 

$type 字段类型

db.things.find( { a : { $type : 2 } } )
条件是a类型符合的话返回数据。

 

limit() skip()

这两个ME想连起来讲,他们就是你实现数据库分页的好帮手。
limit()控制返回结果数量,如果参数是0,则当作没有约束,limit()将不起作用。
skip()控制返回结果跳过多少数量,如果参数是0,则当作没有约束,skip()将不起作用,或者说跳过了0条。
例如:
 db.test.find().skip(5).limit(5)
结果就是取第6条到第10条数据。
snapshot()   (没有尝试)
count()   条数
返回结果集的条数。
db.test.count()
在加入skip()和limit()这两个操作时,要获得实际返回的结果数,需要一个参数true,否则返回的是符合查询条件的结果总数。
例子如下:
> db.test.find().skip(5).limit(5).count()
9
> db.test.find().skip(5).limit(5).count(true)
4

11) $elemMatch

如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
 t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 
{ "_id" : ObjectId("4b5783300334000000000aa9"), 
"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
}
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
 t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 

12) 查询嵌入对象的值

db.postings.find( { "author.name" : "joe" } );
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
 db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
如果我们要查询 authors name 是Jane的, 我们可以这样:
 db.blog.findOne({"author.name" : "Jane"})
如果不用点,那就需要用下面这句才能匹配:
db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
下面这句:
db.blog.findOne({"author" : {"name" : "Jane"}})
是不能匹配的,因为mongodb对于子对象,他是精确匹配。

点击查看原文阅读(166) | 评论(0) | 分类:NoSQL

MongoDB数据库导入与导出 (2011-11-21)

 MongoDB的备份(mongodump)与恢复(mongorestore)

一、备份

先介绍下命令语法:

mongodump -h dbhost -d dbname -o dbdirectory

-h:MongDB所在服务器地址,例如:127.0.0.1,当然也可以指定端口号:127.0.0.1:27017

-d:需要备份的数据库实例,例如:test

-o:备份的数据存放位置,例如:/data0/backup,当然该目录需要提前建立,在备份完成后,系统自动在dump目录下建立一个test目录,这个目录里面存放该数据库实例的备份数据。

 

二、恢复

mongorestore -h dbhost -d dbname –directoryperdb dbdirectory

例如:/usr/wangzhen/mongodb-linux-x86_64-2.0.1/bin/mongorestore --directoryperdb /usr/wangzhen/xikang

-h:MongoDB所在服务器地址

-d:需要恢复的数据库实例,例如:test,当然这个名称也可以和备份时候的不一样,比如test2

–directoryperdb:备份数据所在位置,例如:/data0/backup/test,这里为什么要多加一个test,而不是备份时候的backup,读者自己查看提示吧!

–drop:恢复的时候,先删除当前数据,然后恢复备份的数据。就是说,恢复后,备份后添加修改的数据都会被删除,慎用哦!

点击查看原文阅读(305) | 评论(0) | 分类:NoSQL

couldn’t connect to server 127.0.0.1 shell/mongo.js:79 (2011-11-20)

 MongoDB启动报错couldn’t connect to server 127.0.0.1 shell/mongo.js:79
解决如下

1.启动 /usr/wangzhen/mongodb-linux-x86_64-2.0.1/bin/mongod
2. rm /data/db/mongod.lock

点击查看原文阅读(295) | 评论(0) | 分类:NoSQL

LInux下MongoDB安装 (2011-11-11)

linux下安装和配置mongodb
步骤一:下载文件

对于32位的linux
$ curl http://downloads.mongodb.org/linux/mongodb-linux-i686-1.4.4.tgz > mongo.tgz
$ tar xzf mongo.tgz

对于64位的linux
$ curl http://downloads.mongodb.org/linux/mongodb-linux-x86_64-1.4.4.tgz > mongo.tgz
$ tar xzf mongo.tgz

如果没有安装curl 先安装apt-get install curl

步骤二:创建数据文件夹 默认情况下,MongoDB会在/data/db/这个文件夹存放数据,这个文件夹需要自己手动创建。 通过如下方式创建:

$ adduser mongodb
$ passwd mongodb
$ sudo mkdir -p /data/db/
$ sudo chown `id -u` /data/db
$ chown -R mongodb:mongodb /data

当然 可以 通过--dbpath 命令 指定MongoDB将数据存储到另外的目录中去。

步骤三:让数据库运行起来 在控制台中:

$ nohup ./mongodb-xxxxxxx/bin/mongod &
$ ./mongodb-xxxxxxx/bin/mongo
> db.foo.save( { a : 1 } )
> db.foo.find()
或
 ./mongodb-linux-x86_64-1.4.4/bin/mongod

加入开机启动项里 vim /etc/rc.local 加入如下代码保存即可:

#add mongonDB service
/usr/local/webserver/mongodb/bin/mongod –dbpath /data/db –logpath /data/mongodb_log/mongodb.log –logappend –rest &

注:将mongo作为系统命令使用,使其在任何目录下可用:

cp   /usr/local/webserver/mongodb/bin/mongo     /usr/bin/

安装MongoDB PHP扩展
根据自己的PHP版本下载PHP扩展:http://github.com/mongodb/mongo-php-driver/downloads,
提示:
1、VC6适合Apache、VC9适合IIS;
2、Thread safe适合PHP以模块运行方式、Non-thread safe适合CGI运行方式。
修改php.ini,加入:extension=php_mongo.dll,重启Web服务器。

用PHP程序测试一下,成功!
$conn = new Mongo("192.168.12.129:27017");
$db = $conn->selectDB("test");
//$db = $conn->test;
$collection = $db->shicai;
$rows = $collection->find();
print_r($rows); exit;

点击查看原文阅读(223) | 评论(0) | 分类:NoSQL