从MongoDB中的数组中删除对象?
要从MongoDB中的数组中删除对象,可以使用$pull运算符。语法如下:
db.yourCollectionName.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},{$pull:{"yourArrayName":{"yourArrayFieldName":yourValue}}},
false,true);
为了理解上述语法,让我们创建一个带有文档的集合。用于创建包含文档的集合的查询如下:
> db.removeObject.insertOne({"CustomerName":"Maxwell","CustomerAge":23,... "CustomerDetails":[
... {
... "CustomerId":100,
... "CustomerProduct":"Product-1"
... },
... {
... "CustomerId":150,
... "CustomerProduct":"Product-2"
... },
... {
... "CustomerId":200,
... "CustomerProduct":"Product-3"
... }
... ]
... });
{
"acknowledged" : true,
"insertedId" : ObjectId("5c6ea036a0c51185aefbd14f")
}
在find()
method的帮助下显示集合中的所有文档。查询如下:
> db.removeObject.find().pretty();
以下是输出:
{"_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
"CustomerName" : "Maxwell",
"CustomerAge" : 23,
"CustomerDetails" : [
{
"CustomerId" : 100,
"CustomerProduct" : "Product-1"
},
{
"CustomerId" : 150,
"CustomerProduct" : "Product-2"
},
{
"CustomerId" : 200,
"CustomerProduct" : "Product-3"
}
]
}
这是从MongoDB中的数组中删除对象的查询:
> db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},... {$pull:{"CustomerDetails":{"CustomerId":150}}},
... false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
上面,我们从数组中删除了对象。让我们显示集合中的文档。查询如下:
> db.removeObject.find().pretty();
以下是输出:
{"_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
"CustomerName" : "Maxwell",
"CustomerAge" : 23,
"CustomerDetails" : [
{
"CustomerId" : 100,
"CustomerProduct" : "Product-1"
},
{
"CustomerId" : 200,
"CustomerProduct" : "Product-3"
}
]
}
以上是 从MongoDB中的数组中删除对象? 的全部内容, 来源链接: utcz.com/z/356781.html