获取嵌套字符串数组的 MongoDB 查询?


要在 MongoDB 中获取嵌套字符串数组,请在 find() 中使用点表示法。我们创建一个包含文档的集合 -

> db.demo89.insertOne(
... { id: 101, Details: [ { Name: "Chris", Marks: 45 }, { Name: "David", Marks: 55, Subjects : ["MySQL", "MongoDB", "Java", "C"] } ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c163b79799acab037af51")
}
> db.demo89.insertOne(
... { id: 102, Details: [ { Name: "Mike", Marks: 48 }, { Name: "Bob", Marks: 98, Subjects : ["C++", "MySQL"] } ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c163c79799acab037af52")
}

使用 find() 方法显示集合中的所有文档 -

> db.demo89.find();

这将生成以下输出 -

{ "_id" : ObjectId("5e2c163b79799acab037af51"), "id" : 101, "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "David", "Marks" : 55, "Subjects" : [ "MySQL", "MongoDB", "Java", "C" ] } ] }
{ "_id" : ObjectId("5e2c163c79799acab037af52"), "id" : 102, "Details" : [ { "Name" : "Mike", "Marks" : 48 }, { "Name" : "Bob", "Marks" : 98, "Subjects" : [ "C++", "MySQL" ] } ] }

以下是获取嵌套字符串数组的查询 -

> db.demo89.find({ "Details.Subjects": "MongoDB"});

这将生成以下输出 -

{ "_id" : ObjectId("5e2c163b79799acab037af51"), "id" : 101, "Details" : [ { "Name" : "Chris", "Marks" : 45 }, { "Name" : "David", "Marks" : 55, "Subjects" : [ "MySQL", "MongoDB", "Java", "C" ] } ] }

更新于:30-03-2020

242 次浏览

开启您的 职业生涯

完成课程后获得认证

开始
广告