MongoDBで1回の更新呼び出しを使用して、ドキュメント内の2つの別々の配列を更新しますか?
これには$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での1回の更新呼び出しで2つの別々の配列をプッシュするクエリです
> db.twoSeparateArraysDemo.update({_id:ObjectId("5c9b152d15e86fd1496b38b9")}, { $push : {
StudentFirstGameScore : 45, StudentSecondGameScore : 99}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 値が2つの別々の配列にプッシュされているかどうかを確認しましょう
> 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
]
} -
1つのMongoDBドキュメントの2つの配列内で一意の値を取得する
ドキュメント内の2つの配列内で一意の値を取得するには、aggregate()で$setUnionを使用します。 $ setUnionは、2つ以上の配列を受け取り、任意の入力配列に表示される要素を含む配列を返します。 ドキュメントを使用してコレクションを作成しましょう- >db.demo608.insertOne({"ListOfName1":["John","Chris","Bob","David"],"ListOfName2":["Bob", &
-
MongoDBで1つのクエリで多くのドキュメントを更新するにはどうすればよいですか?
1つのクエリで多くのドキュメントを更新するには、MongoDBでbulkWrite()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo760.insertOne({id:1,details:{Value1:100,Value2:50}}); { "acknowledged" : true, "insertedId" : ObjectId("5eb0309f5637cd592b2a4aee") } > db.demo760.insert