从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"
}
]
}热门推荐
10 祝产妇的祝福语简短
11 上级买车祝福语大全简短
12 对睡觉的祝福语简短
13 毕业英语祝福语大全简短
14 新年简短的英文祝福语
15 祝福语简短唯美10字
16 祝朋友祝福语简短好看
17 二胎祝福语简短霸气
18 对上司的简短祝福语