MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBのJSON配列の内部要素にアクセスしますか?


MongoDBのJSON配列の内部要素にアクセスするには、ドット表記を使用します。ドキュメントを使用してコレクションを作成しましょう-

> db.demo687.insert({CountryName:'US',
... info:
... {
... id:101,
... details:
... [
... {
...    Name:'Chris',
...    SubjectName:'MongoDB',
...    otherDetails:{
...       "Marks":58,
...       Age:23
...    }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })
> db.demo687.insert({CountryName:'UK',
... info:
... {
... id:102,
... details:
... [
... {
...    Name:'David',
...    SubjectName:'MySQL',
...    otherDetails:{
...       "Marks":78,
...       Age:21
...    }
... }
... ]
... }
... }
... )
WriteResult({ "nInserted" : 1 })

find()メソッドを使用してコレクションからすべてのドキュメントを表示する-

> db.demo687.find();

これにより、次の出力が生成されます-

{ "_id" : ObjectId("5ea55658a7e81adc6a0b3962"), "CountryName" : "US", "info" : { "id" : 101, "details" : [ { "Name" : "Chris", "SubjectName" : "MongoDB", "otherDetails" : { "Marks" : 58, "Age" : 23 } } ] } }
{ "_id" : ObjectId("5ea55673a7e81adc6a0b3963"), "CountryName" : "UK", "info" : { "id" : 102, "details" : [ { "Name" : "David", "SubjectName" : "MySQL", "otherDetails" : { "Marks" : 78, "Age" : 21 } } ] } }

以下は、JSON配列の内部要素にアクセスするためのクエリです-

> db.demo687.find({"info.details.otherDetails.Marks":58});

これにより、次の出力が生成されます-

{ "_id" : ObjectId("5ea55658a7e81adc6a0b3962"), "CountryName" : "US", "info" : { "id" : 101, "details" : [ { "Name" : "Chris", "SubjectName" : "MongoDB", "otherDetails" : { "Marks" : 58, "Age" : 23 } } ] } }

  1. MongoDBの配列から要素を削除するにはどうすればよいですか?

    配列から要素を削除するには、$pullを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo279.insertOne({id:[101,103,105,110]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e490af7dd099650a5401a58") } > db.demo279.insertOne({id:[107,111,110]}); {    

  2. MongoDB配列の要素を削除するにはどうすればよいですか?

    要素を削除するには、MongoDBで$ pullを更新して、使用します。 $ pull演算子は、既存の配列から、指定された条件に一致する1つまたは複数の値のすべてのインスタンスを削除します。 まず、ドキュメントを使用してコレクションを作成しましょう- db.demo541.insertOne({"software":{"services":["gmail","facebook","yahoo"]}});{    "acknowledged" : true