在MongoDB中使用一个更新调用来更新文档中的两个单独的数组?
您可以为此使用$push运算符。首先让我们创建一个包含文档的集合
>db.twoSeparateArraysDemo.insertOne({"StudentName":"Larry","StudentFirstGameScore":[98],"StudentSecondGameScore":[77]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b152815e86fd1496b38b8")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"Mike","StudentFirstGameScore":[58],"StudentSecondGameScore":[78]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b152d15e86fd1496b38b9")
}
>db.twoSeparateArraysDemo.insertOne({"StudentName":"David","StudentFirstGameScore":[65],"StudentSecondGameScore":[67]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b153315e86fd1496b38ba")
}以下是在find()方法的帮助下显示集合中所有文档的查询
> db.twoSeparateArraysDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5c9b152815e86fd1496b38b8"),
"StudentName" : "Larry",
"StudentFirstGameScore" : [
98
],
"StudentSecondGameScore" : [
77
]
}
{
"_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
"StudentName" : "Mike",
"StudentFirstGameScore" : [
58
],
"StudentSecondGameScore" : [
78
]
}
{
"_id" : ObjectId("5c9b153315e86fd1496b38ba"),
"StudentName" : "David",
"StudentFirstGameScore" : [
65
],
"StudentSecondGameScore" : [
67
]
}以下是在MongoDB中的一个更新调用中将两个单独的数组推入的查询
> db.twoSeparateArraysDemo.update({_id:ObjectId("5c9b152d15e86fd1496b38b9")}, { $push : {
StudentFirstGameScore : 45, StudentSecondGameScore : 99}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })让我们检查是否将值压入两个单独的数组中
> db.twoSeparateArraysDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5c9b152815e86fd1496b38b8"),
"StudentName" : "Larry",
"StudentFirstGameScore" : [
98
],
"StudentSecondGameScore" : [
77
]
}
{
"_id" : ObjectId("5c9b152d15e86fd1496b38b9"),
"StudentName" : "Mike",
"StudentFirstGameScore" : [
58,
45
],
"StudentSecondGameScore" : [
78,
99
]
}
{
"_id" : ObjectId("5c9b153315e86fd1496b38ba"),
"StudentName" : "David",
"StudentFirstGameScore" : [
65
],
"StudentSecondGameScore" : [
67
]
}