如何确定 MongoDB 查询中是否存在特定值?
若要确定某个特定值是否存在,请在 MongoDB 中使用 $ne。我们创建一个包含文书的集合 -
> db.demo206.insertOne(
... {
... "ClientDetails":
... [
... {
... "Name":"Chris",
... "Age":28,
... "CountryName":"US"
... }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3d8bd403d395bdc21346ee")
}
> db.demo206.insertOne(
... {
... "ClientDetails":
... [
... {
... "Name":"David",
... "Age":29,
... "CountryName":"UK"
... }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3d8bd403d395bdc21346ef")
}
>
> db.demo206.insertOne(
... {
... "ClientDetails":
... [
... {
... "Name":"Bob",
... "Age":31,
... "CountryName":"US"
... }
... ]
... }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3d8bd503d395bdc21346f0")
}使用 find() 方法显示集合中的所有文书 -
> db.demo206.find();
将生成以下输出 -
{ "_id" : ObjectId("5e3d8bd403d395bdc21346ee"), "ClientDetails" : [ { "Name" : "Chris", "Age" : 28, "CountryName" : "US" } ] }
{ "_id" : ObjectId("5e3d8bd403d395bdc21346ef"), "ClientDetails" : [ { "Name" : "David", "Age" : 29, "CountryName" : "UK" } ] }
{ "_id" : ObjectId("5e3d8bd503d395bdc21346f0"), "ClientDetails" : [ { "Name" : "Bob", "Age" : 31, "CountryName" : "US" } ] }以下是确定特定值是否存在的查询 -
> db.demo206.find({"ClientDetails.CountryName": {"$ne": "US"}});将生成以下输出 -
{ "_id" : ObjectId("5e3d8bd403d395bdc21346ef"), "ClientDetails" : [ { "Name" : "David", "Age" : 29, "CountryName" : "UK" } ] }
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP