Open msforest opened 6 years ago
https://docs.mongodb.com/manual/reference/operator/
db.articles.aggregate({$project: {author: 1}},
{$group: {_id: '$author', count: {$sum: 1}}},
{$sort: {count: -1}},
{$limit: 5})
// rename: _id => id db.test.aggregate({$project: {id: '$_id', _id: 0}})
2. 数学操作法
- $add : [expr1[, expr2, ..., exprN]]
- $subtract : [expr1, expr2]
- $multiply : [expr1[, expr2, ..., exprN]]
- $divide : [expr1, expr2]
- $mod : [expr1, expr2]
db.test.aggregate({$project: {total: {$subtract: [{$add: ['$a', '$b']}, '$c']}}})
3. 日期表达式
- $year
- $month
- $week
- $dayOfMonth
- $dayOfWeek
- $dayOfYear
- $hour
- $minute
- $second
db.test.aggregate({$project: {hireIn: {$month: '$hireDate'}}})
4. 字符串表达式
- $substr : [expr, startOffset, numToReturn]
- $concat : [expr1[, expr2, ..., expr3]]
- $toLower
- $toUpper
5. 其他
- $cmp
- $strcasecmp
- $ne / $eq / $lt / $lte / $gt / $gte
- $and / $or / $not / $in /$nin
- $slice / $inc / $push / $each / $addToSet / $pop / $pull
<hr>
//{ "_id" : ObjectId("5ace21a69ef8360d70cbf73c"), "a" : 1, "b" : [ { "a" : 2 }, { "a" : 3 }, { "a" : 5 } ] }
db.test.find({'b.a': 3}, {'b.$': 1}) //{ "_id" : ObjectId("5ace21a69ef8360d70cbf73c"), "b" : [ { "a" : 3 } ] } 只列出匹配的一个
db.test.find({a: 1}, {b: {$slice: 1}}) // { "_id" : ObjectId("5ace21a69ef8360d70cbf73c"), "a" : 1, "b" : [ { "a" : 2 } ] } 只列出第一个
// {x: 1}, {x: [14]}, {x: [5, 15]}
db.test.find({x: {$elemMatch: {$gt: 10, $lt: 30}}}) //typeof x === array // {x: [14]}
db.test.find({x: {$gt: 10, $lt: 30}}) // {x: 1}, {x: [14]}, {x: [5, 15]}
[top](#210)
如何搭建副本集,参考《MongoDB权威指南第2版》:第9章节
- 在本地搭建副本集时,执行
replicaSet.startSet()
报错this.getDB of undefined.
往回看第一个命令
replicaSet = new ReplSetTest({node: 3})
时发现ports
属性为空数组,然后把本机的主机名改为“localhost”就好了
replicaSet.initiate()
报错
No host described in new configuration 1 for replica set __unknown_name__ maps to this node
经过查找,https://dotmanila.com/2015/11/mongodb-no-host-in-new-replica-set-maps-to-this-node/
这里列出三点,最重要的是说重新核对replica set config,一看replicaSet.startSet()
生成的host是name.xx.-book:20000
,导致无法解析主机名,然后自己重新定义配置
config = {
_id: '__unknown_name__', // from cmd `ps -ef|grep mongo`, --replSet __unknown_name__
members: [
{
_id: 0,
host: 'localhost:20000'
},
...
]
}
replicaSet.initiate(config)
[top](#210)
导入导出
查看服务器的命令行参数