从MongoDB数组中删除空元素?
您可以为此使用$pull运算符。首先让我们创建一个包含文档的集合-
> db.removeNullDemo.insertOne(... {
... "_id" : 1,
... "StudentDetails" : [
... {
... "FirstName": "John",
... "LastName":"Smith",
...
... },
... {
... "Age":21
... },
... null
...
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 1 }
> db.removeNullDemo.insertOne(
... {
... "_id" : 2,
... "StudentDetails" : [
... {
... "FirstName": "Carol",
... "LastName":"Taylor",
...
... },
... {
... "Age":23
... }
...
...
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 2 }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.removeNullDemo.find().pretty();
这将产生以下输出-
{"_id" : 1,
"StudentDetails" : [
{
"FirstName" : "John",
"LastName" : "Smith"
},
{
"Age" : 21
},
null
]
}
{
"_id" : 2,
"StudentDetails" : [
{
"FirstName" : "Carol",
"LastName" : "Taylor"
},
{
"Age" : 23
}
]
}
以下是从MongoDB数组中删除null元素的查询-
> db.removeNullDemo.update({_id:1},{$pull:{StudentDetails:null}});WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们检查null是否已删除-
> db.removeNullDemo.find().pretty();
这将产生以下输出-
{"_id" : 1,
"StudentDetails" : [
{
"FirstName" : "John",
"LastName" : "Smith"
},
{
"Age" : 21
}
]
}
{
"_id" : 2,
"StudentDetails" : [
{
"FirstName" : "Carol",
"LastName" : "Taylor"
},
{
"Age" : 23
}
]
}
以上是 从MongoDB数组中删除空元素? 的全部内容, 来源链接: utcz.com/z/338551.html