如何无条件地从 MongoDB 中的数组提取全部元素?
你可以为此使用 $set 操作符。让我们首先创建一个包含文档的集合 -
> db.pullAllElementDemo.insertOne(
... {
... "StudentId":101,
... "StudentDetails" : [
... {
...
... "StudentName": "Carol",
... "StudentAge":21,
... "StudentCountryName":"US"
... },
... {
... "StudentName": "Chris",
... "StudentAge":24,
... "StudentCountryName":"AUS"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdd9c8685b30d09a7111e4")
}
> db.pullAllElementDemo.insertOne(
... {
... "StudentId":102,
... "StudentDetails" : [
... {
...
... "StudentName": "Robert",
... "StudentAge":27,
... "StudentCountryName":"UK"
... },
... {
... "StudentName": "David",
... "StudentAge":23,
... "StudentCountryName":"US"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdd9f7685b30d09a7111e5")
}以下是使用 find() 方法显示集合中所有文档的查询 -
> db.pullAllElementDemo.find().pretty();
这将产生以下输出 -
{
"_id" : ObjectId("5ccdd9c8685b30d09a7111e4"),
"StudentId" : 101,
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
]
}
{
"_id" : ObjectId("5ccdd9f7685b30d09a7111e5"),
"StudentId" : 102,
"StudentDetails" : [
{
"StudentName" : "Robert",
"StudentAge" : 27,
"StudentCountryName" : "UK"
},
{
"StudentName" : "David",
"StudentAge" : 23,
"StudentCountryName" : "US"
}
]
}以下是无条件地从 MongoDB 中的数组提取所有元素的查询。在此,我们已使用 $set 删除具有 StudentId 102 的 StudentDetails -
> db.pullAllElementDemo.update( {StudentId:102}, { "$set": { "StudentDetails": [] }} );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })让我们显示来自上述集合的所有文档,以检查特定元素是否已从数组中提取出来 -
> db.pullAllElementDemo.find().pretty();
这将产生以下输出 -
{
"_id" : ObjectId("5ccdd9c8685b30d09a7111e4"),
"StudentId" : 101,
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
]
}
{
"_id" : ObjectId("5ccdd9f7685b30d09a7111e5"),
"StudentId" : 102,
"StudentDetails" : [ ]
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP