数组对象中的 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" ] } } }
广告