本篇文章给大家分享的是有关如何进行MongoDB排除查询$ne缺陷,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
最近学习MongoDB数据库基本开发知识,发现MongoDB的排除查$ne类似于Oracle的not in 或者not exists,
但是$ne只能对字符串键值对起作用而对数字类型不行,举例如下:
示例数据:
> dvd=({"Type":"DVD","Title":"Matrix,The","Released":1999,"Cast":["Keanu Reeeves","Carrie-Anne Moss","Laurence Fishburne","Hugo Weaving","Gloria Foster","Joe Pantoliano"]})
{
"Type" : "DVD",
"Title" : "Matrix,The",
"Released" : 1999,
"Cast" : [
"Keanu Reeeves",
"Carrie-Anne Moss",
"Laurence Fishburne",
"Hugo Weaving",
"Gloria Foster",
"Joe Pantoliano"
]
}
> db.media.insert(dvd)
WriteResult({ "nInserted" : 1 })
> dvd=({"Type":"DVD","Title":"Blade Runner","Released":1982})
{ "Type" : "DVD", "Title" : "Blade Runner", "Released" : 1982 }
> db.media.insert(dvd)
WriteResult({ "nInserted" : 1 })
> dvd=({"Type":"DVD","Title":"Toy Story 3","Released":2010})
{ "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
> db.media.insert(dvd)
WriteResult({ "nInserted" : 1 })
>
正常的字符串排除查询,以示例数据中Title键进行测试:
> db.media.find({"Type":"DVD","Title":{$ne:"Blade Runner"}})
{ "_id" : ObjectId("595af5ce39297105e4322fbd"), "Type" : "DVD", "Title" : "Matrix,The", "Released" : 1999, "Cast" : [ "Keanu Reeeves", "Carrie-Anne Moss", "Laurence Fishburne", "Hugo Weaving", "Gloria Foster", "Joe Pantoliano" ] }
{ "_id" : ObjectId("595af63239297105e4322fbf"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
对数字排除无效,以示例数据中Released键进行测试:
> db.media.find({"Type":"DVD","Release":{$ne:"1999"}})
{ "_id" : ObjectId("595af5ce39297105e4322fbd"), "Type" : "DVD", "Title" : "Matrix,The", "Released" : 1999, "Cast" : [ "Keanu Reeeves", "Carrie-Anne Moss", "Laurence Fishburne", "Hugo Weaving", "Gloria Foster", "Joe Pantoliano" ] }
{ "_id" : ObjectId("595af61939297105e4322fbe"), "Type" : "DVD", "Title" : "Blade Runner", "Released" : 1982 }
{ "_id" : ObjectId("595af63239297105e4322fbf"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
> db.media.find({"Type":"DVD","Release":{$ne:1999}})
{ "_id" : ObjectId("595af5ce39297105e4322fbd"), "Type" : "DVD", "Title" : "Matrix,The", "Released" : 1999, "Cast" : [ "Keanu Reeeves", "Carrie-Anne Moss", "Laurence Fishburne", "Hugo Weaving", "Gloria Foster", "Joe Pantoliano" ] }
{ "_id" : ObjectId("595af61939297105e4322fbe"), "Type" : "DVD", "Title" : "Blade Runner", "Released" : 1982 }
{ "_id" : ObjectId("595af63239297105e4322fbf"), "Type" : "DVD", "Title" : "Toy Story 3", "Released" : 2010 }
>
实验结果:mongodb的$ne操作只能对字符串键值对发挥作用。
本次实验的MongoDB数据库版本是:3.2.7
以上就是如何进行MongoDB排除查询$ne缺陷,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。