问题描述
{
"_id" : ObjectId("5f577f3cce031ee00f5e32c9"),"UserId" : 0,"firstname" : "user 1","lastname" : "user 1","finishedTrainings" : [
{
"itemId" : 3,"validationscore" : 1,"timestamps" : {
"createdat" : ISODate("2020-09-09T12:57:31.275Z"),"createdby" : 0,"updatedat" : ISODate("0001-01-01T00:00:00Z"),"updatedby" : 0
},"isValidated" : true
},{
"itemId" : 0,"validationscore" : 0.6666666666666666,"timestamps" : {
"createdat" : ISODate("2020-09-09T12:59:04.268Z"),"isValidated" : true
}
],"biography" : ""
}
我想删除finishedTraining(id = 3),mongodb中的语法是什么
解决方法
//从mongo shell 4.2,windows10输出的代码
//data set as given in problem statement
> db.userTraining.find().pretty();
{
"_id" : ObjectId("5f577f3cce031ee00f5e32c9"),"UserId" : 0,"firstname" : "user 1","lastname" : "user 1","finishedTrainings" : [
{
"itemId" : 3,"validationScore" : 1,"timestamps" : {
"createdat" : ISODate("2020-09-09T12:57:31.275Z"),"createdby" : 0,"updatedat" : ISODate("0001-01-01T00:00:00Z"),"updatedby" : 0
},"isValidated" : true
},{
"itemId" : 0,"validationScore" : 0.6666666666666666,"timestamps" : {
"createdat" : ISODate("2020-09-09T12:59:04.268Z"),"isValidated" : true
}
],"biography" : ""
}
//assuming objectID is unique for the document,you can query your own business field
> db.userTraining.update(
... {_id:ObjectId("5f577f3cce031ee00f5e32c9")},... {$pull:{"finishedTrainings":{itemId:3}}},... false,... true
... );
WriteResult({ "nMatched" : 1,"nUpserted" : 0,"nModified" : 1 })
> db.userTraining.find().pretty();
{
"_id" : ObjectId("5f577f3cce031ee00f5e32c9"),"finishedTrainings" : [
{
"itemId" : 0,"biography" : ""
}
>
//above id=3 is deleted object from the array,other document object remain intact by using "$pull" in the update statement