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

配列内のすべてのオブジェクトが特定の値を持つMongoDBドキュメントを検索しますか?


ドキュメントを使用してコレクションを作成しましょう-

> db.demo74.insertOne(
... {
... StudentName: "Chris",
... StudentDetails: [{
...    "Subject": "MongoDB",
...    "isRegular": "Active"
...    },{
...       "Subject": "MongoDB",
...       "isRegular": "InActive"
...    },{
...       "Subject": "MongoDB",
...       "isRegular": "InActive"
...    }]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29c6b671bf0181ecc4226f")
}
> db.demo74.insertOne({
... name: "document2",
... data: [{
...    "Subject": "MongoDB",
...    "isRegular": "Active"
...    },{
...       "Subject": "MongoDB",
...       "isRegular": "Active"
...    },{
...       "Subject": "MongoDB",
...       "isRegular": "Active"
...    }]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e29c6b771bf0181ecc42270")
}

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

> db.demo74.find();

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

{
   "_id" : ObjectId("5e29c6b671bf0181ecc4226f"), "StudentName" : "Chris", "StudentDetails" : [
      { "Subject" : "MongoDB", "isRegular" : "Active" },
      { "Subject" : "MongoDB", "isRegular" : "InActive" },
      { "Subject" : "MongoDB", "isRegular" : "InActive" }
   ]
}
{
   "_id" : ObjectId("5e29c6b771bf0181ecc42270"), "name" : "document2", "data" : [
      { "Subject" : "MongoDB", "isRegular" : "Active" },
      { "Subject" : "MongoDB", "isRegular" : "Active" },
      { "Subject" : "MongoDB", "isRegular" : "Active" }
   ] 
}

以下は、配列内のすべてのオブジェクトが特定の値を持つドキュメントを検索するためのクエリです-

> db.demo74.find({ " StudentDetails": { "$not": { "$elemMatch": { "isRegular": { $ne: "Active" } } } }, "StudentDetails.isRegular": "Active" }).pretty();

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

{
   "_id" : ObjectId("5e29c6b671bf0181ecc4226f"),
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "Subject" : "MongoDB",
         "isRegular" : "Active"
      },
      {
         "Subject" : "MongoDB",
         "isRegular" : "InActive"
      },
      {
         "Subject" : "MongoDB",
         "isRegular" : "InActive"
      }
   ]
}

  1. MongoDBを使用して、特定のネストされたドキュメントのオブジェクトの配列をクエリしますか?

    ネストされたドキュメントのオブジェクトの配列をクエリするには、find()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo763.insertOne( ...    { ...       _id:1, ...       CountryName:"US", ...       "studentInformation": [ ...          {

  2. MongoDBで配列をクエリして、特定の値をフェッチします

    配列から特定の値をフェッチするには、$ projectとともにaggregate()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo761.insertOne( ...    { ...       "details": [ ...          { ...             "student": { ...     &nb