MongoDB查询数组的对象
首先让我们创建一个包含文档的集合-
> db.demo194.insertOne( ... { ... "_id": 101, ... "details": { ... "otherDetails": { ... "List1": ["MongoDB", "MySQL"], ... "List2": ["Java"], ... "List3": ["MongoDB", "C"] ... } ... } ... } ...); { "acknowledged" : true, "insertedId" : 101 } > db.demo194.insertOne( {"_id": 102, "details": { "otherDetails": { "List1": ["Java", "C"], "List2": ["C++"], "List3": ["Python", "Spring"] } } } ); { "acknowledged" : true, "insertedId" : 102 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo194.find();
这将产生以下输出-
{ "_id" : 101, "details" : { "otherDetails" : { "List1" : [ "MongoDB", "MySQL" ], "List2" : [ "Java" ], "List3" : [ "MongoDB", "C" ] } } } { "_id" : 102, "details" : { "otherDetails" : { "List1" : [ "Java", "C" ], "List2" : [ "C++" ], "List3" : [ "Python", "Spring" ] } } }
这是如何查询数组的对象-
> db.demo194.find({ "details.otherDetails.List1": "MongoDB" })
这将产生以下输出-
{ "_id" : 101, "details" : { "otherDetails" : { "List1" : [ "MongoDB", "MySQL" ], "List2" : [ "Java" ], "List3" : [ "MongoDB", "C" ] } } }