查找包含特定字段的MongoDB文档?
要查找包含特定字段的文档,请使用$exists。让我们创建一个包含文档的集合-
> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"Chris","ClientAge":34}]});{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b2a31627c0c63e7dba69")
}
>db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"John","ClientLastName":"Smith","ClientAge":31}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b2be1627c0c63e7dba6a")
}
> db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientAge":33}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b2cd1627c0c63e7dba6b")
}
>db.demo247.insertOne({"ClientDetails":[{"ClientFirstName":"David","ClientLastName":"Miller","ClientAge":31}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e46b2de1627c0c63e7dba6c")
}
在find()方法的帮助下显示集合中的所有文档-
> db.demo247.find().pretty();
这将产生以下输出-
{"_id" : ObjectId("5e46b2a31627c0c63e7dba69"),
"ClientDetails" : [
{
"ClientFirstName" : "Chris",
"ClientAge" : 34
}
]
}
{
"_id" : ObjectId("5e46b2be1627c0c63e7dba6a"),
"ClientDetails" : [
{
"ClientFirstName" : "John",
"ClientLastName" : "Smith",
"ClientAge" : 31
}
]
}
{
"_id" : ObjectId("5e46b2cd1627c0c63e7dba6b"),
"ClientDetails" : [
{
"ClientFirstName" : "David",
"ClientAge" : 33
}
]
}
{
"_id" : ObjectId("5e46b2de1627c0c63e7dba6c"),
"ClientDetails" : [
{
"ClientFirstName" : "David",
"ClientLastName" : "Miller",
"ClientAge" : 31
}
]
}
以下是查找包含特定字段的文档的查询-
> db.demo247.find({"ClientDetails.ClientLastName":{$exists:true}});
这将产生以下输出-
{"_id" : ObjectId("5e46b2be1627c0c63e7dba6a"), "ClientDetails" : [
{ "ClientFirstName" : "John", "ClientLastName" : "Smith", "ClientAge" : 31 }
]
}
{
"_id" : ObjectId("5e46b2de1627c0c63e7dba6c"), "ClientDetails" : [
{ "ClientFirstName" : "David", "ClientLastName" : "Miller", "ClientAge" : 31 }
]
}
以上是 查找包含特定字段的MongoDB文档? 的全部内容, 来源链接: utcz.com/z/335380.html