MongoDB中怎么实现逻辑运算
本篇文章给大家分享的是有关MongoDB中怎么实现逻辑运算,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
逻辑运算注意就是三种类型:与($and)、或($or),非($not,$nor)。
范例:查询年龄在20~30岁的人员信息
> db.emp.find({"age":{"$gte":20,"$lte":30}}).pretty();
{
"_id" : ObjectId("599108423268c8e84253be26"),
"name" : "赵一",
"sex" : "男",
"age" : 30,
"sal" : 1000,
"loc" : "北京"
}
{
"_id" : ObjectId("599108423268c8e84253be27"),
"name" : "钱二",
"sex" : "女",
"age" : 22,
"sal" : 5000,
"loc" : "上海"
}
{
"_id" : ObjectId("599108423268c8e84253be29"),
"name" : "李四",
"sex" : "女",
"age" : 30,
"sal" : 7000,
"loc" : "北京"
}
{
"_id" : ObjectId("599108423268c8e84253be2a"),
"name" : "周五",
"sex" : "女",
"age" : 30,
"sal" : 6400,
"loc" : "北京"
}
{
"_id" : ObjectId("599108423268c8e84253be2b"),
"name" : "吴六",
"sex" : "男",
"age" : 30,
"sal" : 2500,
"loc" : "重庆"
在进行逻辑运算的时候"and"的连接是最容易的,因为只需要利用","分隔若干条件就可以了。
范例:查询年龄不是30的人员
> db.emp.find({"age":{"$ne":30}}).pretty();
{
"_id" : ObjectId("599108423268c8e84253be27"),
"name" : "钱二",
"sex" : "女",
"age" : 22,
"sal" : 5000,
"loc" : "上海"
}
{
"_id" : ObjectId("599108423268c8e84253be28"),
"name" : "孙三",
"sex" : "男",
"age" : 40,
"sal" : 2000,
"loc" : "深圳"
}
{
"_id" : ObjectId("599108423268c8e84253be2c"),
"name" : "郑七",
"sex" : "女",
"age" : 50,
"sal" : 4700,
"loc" : "成都"
}
{
"_id" : ObjectId("599108433268c8e84253be2d"),
"name" : "王八",
"sex" : "男",
"age" : 35,
"sal" : 8000,
"loc" : "北京"
}
范例:查询年龄大于30岁,或者薪水大于5000的人员信息
> db.emp.find({"$or":[{"age":{"gt":30}},{"sal":{"$gt":5000}}]}).pretty();
{
"_id" : ObjectId("599108423268c8e84253be29"),
"name" : "李四",
"sex" : "女",
"age" : 30,
"sal" : 7000,
"loc" : "北京"
}
{
"_id" : ObjectId("599108423268c8e84253be2a"),
"name" : "周五",
"sex" : "女",
"age" : 30,
"sal" : 6400,
"loc" : "北京"
}
{
"_id" : ObjectId("599108433268c8e84253be2d"),
"name" : "王八",
"sex" : "男",
"age" : 35,
"sal" : 8000,
"loc" : "北京"
范例:或的求反操作
> db.emp.find({"$nor":[{"age":{"gt":30}},{"sal":{"$gt":5000}}]}).pretty();
{
"_id" : ObjectId("599108423268c8e84253be26"),
"name" : "赵一",
"sex" : "男",
"age" : 30,
"sal" : 1000,
"loc" : "北京"
}
{
"_id" : ObjectId("599108423268c8e84253be27"),
"name" : "钱二",
"sex" : "女",
"age" : 22,
"sal" : 5000,
"loc" : "上海"
}
{
"_id" : ObjectId("599108423268c8e84253be28"),
"name" : "孙三",
"sex" : "男",
"age" : 40,
"sal" : 2000,
"loc" : "深圳"
}
{
"_id" : ObjectId("599108423268c8e84253be2b"),
"name" : "吴六",
"sex" : "男",
"age" : 30,
"sal" : 2500,
"loc" : "重庆"
}
{
"_id" : ObjectId("599108423268c8e84253be2c"),
"name" : "郑七",
"sex" : "女",
"age" : 50,
"sal" : 4700,
"loc" : "成都"
}
针对于或的操作可以实现一个求反的功能。
在这几个逻辑运算当中,与的连接最简单,而或的连接需要为数据设置数组的过滤条件。
以上就是MongoDB中怎么实现逻辑运算,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。