MongoDBでドキュメントを更新するときの条件付きアップサート(複数挿入)?
複数の書き込み操作の場合は、MongoDBでbulkWrite()を使用します。ドキュメントを使用してコレクションを作成しましょう-
> db.demo428.insertOne({ "Name" : "Chris", "Age" : 21 });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e75f428bbc41e36cc3cae83")
}
> db.demo428.insertOne({ "Name" : "Chris", "Age" : 23 });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e75f429bbc41e36cc3cae84")
}
> db.demo428.insertOne({ "Name" : "David", "Age" : 22 });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e75f42abbc41e36cc3cae85")
}
> db.demo428.insertOne({ "Name" : "David", "Age" : 21 });
{
"acknowledged" : true,
"insertedId" : ObjectId("5e75f42abbc41e36cc3cae86")
} find()メソッドを使用してコレクションからすべてのドキュメントを表示する
> db.demo428.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e75f428bbc41e36cc3cae83"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e75f429bbc41e36cc3cae84"), "Name" : "Chris", "Age" : 23 }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae85"), "Name" : "David", "Age" : 22 }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae86"), "Name" : "David", "Age" : 21 } 以下は、MongoDBでドキュメントを更新する際の条件付きアップサート(挿入)のクエリです-
> db.demo428.bulkWrite(
... [
... { "updateOne": {
... "filter": { "Name": "David", "Age": 22 },
... "update": { "$set": { "Info": {Name:"John"} } }
... }},
... { "insertOne": {
... "document": { "Name": "Carol", "Age": 22, "Info": {Name:"John"}}
... }}
... ],
... { "ordered": false }
... )
{
"acknowledged" : true,
"deletedCount" : 0,
"insertedCount" : 1,
"matchedCount" : 1,
"upsertedCount" : 0,
"insertedIds" : {
"1" : ObjectId("5e75f448bbc41e36cc3cae87")
},
"upsertedIds" : {
}
} find()メソッドを使用してコレクションからすべてのドキュメントを表示する-
> db.demo428.find();
これにより、次の出力が生成されます-
{ "_id" : ObjectId("5e75f428bbc41e36cc3cae83"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e75f429bbc41e36cc3cae84"), "Name" : "Chris", "Age" : 23 }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae85"), "Name" : "David", "Age" : 22, "Info" : { "Name" : "John" } }
{ "_id" : ObjectId("5e75f42abbc41e36cc3cae86"), "Name" : "David", "Age" : 21 }
{ "_id" : ObjectId("5e75f448bbc41e36cc3cae87"), "Name" : "Carol", "Age" : 22, "Info" : { "Name" : "John" } } -
MongoDBドキュメントの更新中にカスタム変数を使用するにはどうすればよいですか?
更新するには、update()を使用します。以下は、サンプルのカスタム変数を作成して使用するための構文です- var anyVariableName=yourValue; db.yourCollectionName.update({filter},{$set:{yourFieldName:yourVariableName}}); ドキュメントを使用してコレクションを作成しましょう- > db.demo600.insertOne({id:1,Name:"Robert"});{ "acknowledged" : true,
-
Javaを使用して複数のドキュメントをMongoDBコレクションに挿入するにはどうすればよいですか?
insertMany()を使用して、MongoDBの既存のコレクションに複数のドキュメントを挿入できます。 メソッド。 構文 db.coll.insert(docArray) どこで、 db はデータベースです。 coll ドキュメントを挿入するコレクション(名前)です docArray 挿入するドキュメントの配列です。 例 > use myDatabase() switched to db myDatabase() > db.createCollection(sample) { "ok" : 1 } > d