在MongoDB中查询数组大小大于1的文档?

您可以使用长度查询数组大小大于1的文档:

db.yourCollectionName.find({$where:"this.yourArrayDocumentName.length > 1"}).pretty();

为了理解上述语法,让我们创建包含一些文档的集合。查询如下以创建包含文档的集合:

>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Larry","StudentTechnicalSubje

ct":["Java","C","C++"]});

{

   "acknowledged" : true,

   "insertedId" : ObjectId("5c6d6c4c0c3d5054b766a76a")

}

>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Maxwell","StudentTechnicalSu

bject":["MongoDB"]});

{

   "acknowledged" : true,

   "insertedId" : ObjectId("5c6d6c660c3d5054b766a76b")

}

>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Maxwell","StudentTechnicalSu

bject":["MySQL","SQL Server","PL/SQL"]});

{

   "acknowledged" : true,

   "insertedId" : ObjectId("5c6d6c800c3d5054b766a76c")

}

find()method的帮助下显示集合中的所有文档。查询如下:

> db.arrayLengthGreaterThanOne.find().pretty();

以下是输出:

{

   "_id" : ObjectId("5c6d6c4c0c3d5054b766a76a"),

   "StudentName" : "Larry",

   "StudentTechnicalSubject" : [

      "Java",

      "C",

      "C++"

   ]

}

{

   "_id" : ObjectId("5c6d6c660c3d5054b766a76b"),

   "StudentName" : "Maxwell",

   "StudentTechnicalSubject" : [

      "MongoDB"

   ]

}

{

   "_id" : ObjectId("5c6d6c800c3d5054b766a76c"),

   "StudentName" : "Maxwell",

   "StudentTechnicalSubject" : [

      "MySQL",

      "SQL Server",

      "PL/SQL"

   ]

}

这是对数组大小大于1的文档的查询。以下查询将给出数组大小大于1的所有文档:

> db.arrayLengthGreaterThanOne.find({$where:"this.StudentTechnicalSubject.length > 1"}).pretty();

以下是输出:

{

   "_id" : ObjectId("5c6d6c4c0c3d5054b766a76a"),

   "StudentName" : "Larry",

   "StudentTechnicalSubject" : [

      "Java",

      "C",

      "C++"

   ]

}

{

   "_id" : ObjectId("5c6d6c800c3d5054b766a76c"),

   "StudentName" : "Maxwell",

   "StudentTechnicalSubject" : [

      "MySQL",

      "SQL Server",

      "PL/SQL"

   ]

}

以上是 在MongoDB中查询数组大小大于1的文档? 的全部内容, 来源链接: utcz.com/z/347246.html

回到顶部