1.MongoDB简单查询 "",null,not exists,not "",not null,exists
数据
1.1.在collection集合中查询 filed:null
的数据
db.collection.find({"filed":null});
1.2.在collection集合中查询 filed:not exists
的数据
db.collection.find({"filed":{"$exists":false}});
1.3.在collection集合中查询 filed:null,not exists,""
的数据
db.collection.find({"filed":{"$in":[null,""], "$exists":false}});
1.4.在collection集合中查询 filed:not null
的数据
db.collection.find({"filed":{"$ne":null}});
1.5.在collection集合中查询 filed:exists
存在的数据
db.collection.find({"filed":{"$exists":true}});
1.6.在collection集合中查询 filed:not null,not exists,not ""
的数据
db.collection.find({"filed":{"$nin":[null, ""], "$exists":true}});
需要注意的是,$exists 无法利用到索引, 但 $ne 和 $in 可以用上索引, 所以处于性能的考虑尽可能用 $ne:null。
当然前提是你的字段上有索引。关于索引的查询优化,可以使用性能分析方法 explain()。
2.MongoDB聚合查询
- project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。project:修改输入文档的结构。可以用来重命名、增加或删除域,也可以用于创建计算结果以及嵌套文档。project的 _id字段默认为1是显示状态,不需显示用0表示,其他字段默认为不显示
- match:用于过滤数据,只输出符合条件的文档。match:用于过滤数据,只输出符合条件的文档。match:用于过滤数据,只输出符合条件的文档。match使用MongoDB的标准查询操作。【匹配条件,可选】
- $limit:用来限制MongoDB聚合管道返回的文档数。【结果条数,可选】
- $skip:在聚合管道中跳过指定数量的文档,并返回余下的文档。
- $unwind:将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
- $group:将集合中的文档分组,可用于统计结果。【聚合规则】
- $sort:将输入文档排序后输出。【-1表示降序】
- $geoNear:输出接近某一地理位置的有序文档。
- $project的 _id字段默认为1是显示状态,不需显示用0表示,其他字段默认为不显示
- 官方文档地址:https://docs.mongodb.com/manual/reference/command/aggregate/
- 学习教程地址:https://www.cnblogs.com/dotnet261010/p/8379464.html
db.collection.aggregate([
{
$match: { "filed": /filed/ }
},
{
$group: {
_id: "$filed",
total: { $sum: 1 }
}
},
{
$sort: { total: -1}
},
{
$project: {
_id : 0,
countNumber: "$_id",
totalNumber: "$total"
}
},
{
$skip: 0
},
{
$limit: 1000
}
])
3.MongoDB 查询关键字 $关键词
3.1.关键字【$gt
】,【$gte
】,【$lt
】,【$lte
】
gt:greater than
gte:greater than equals
lt:less than
lte:less than equals
db.collection.find({"filed":{"$gt":NumberLong('7789068869128470528')}})
db.collection.find({"filed":NumberLong('7789068869128470528')});
db.collection.find({"filed":{"$in":[NumberLong("7789068869128470528")]}});
db.collection.find({}).count();
db.collection.aggregate([{
"$group": { "_id":"$filed", count: {"$sum": 1}}
}]);
db.collection.updateMany(
{"filed": {$in:[NumberLong('7789068869128470528')]}},
{$set:{filed:"深圳市柏仑生物科技有限公司"}}
);
//只输出filed字段,第一个参数为查询条件,第二个条件为展示的filed字段,为空则代表展示所有
db.collection.find( {}, { filed: 1 } )
//如果需要输出的字段比较多,不想要某个字段,可以用排除字段的方法
//不输出内容字段,其它字段都输出
db.collection.find( {}, { filed: 0 } )
// 保存
db.userInfo.save({"_id":NumberLong('147258369'), "name":"Andy", "age":NumberInt('18'),"height":NumberInt('165'), "motto" : "First you jump off the cliff and build your wings on the way down.again and again, time will show you the best result!"});
// 查询
db.userInfo.find({},{motto:0});
// 更新
db.userInfo.update({_id:NumberLong('147258369')},{$set:{"hobby":null,"havey":''}});