要在MongoDB中搜索子字段,可以将双引号和点符号一起使用。首先让我们创建一个包含文档的集合-
> db.searchSubFieldDemo.insertOne( ... { ... "UserDetails": ... {"UserEmailId":"John123@gmail.com","UserAge":21} ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd3d909edc6604c74817ce2") } > db.searchSubFieldDemo.insertOne( { "UserDetails": {"UserEmailId":"Carol@yahoo.com","UserAge":26} } ); { "acknowledged" : true, "insertedId" : ObjectId("5cd3d9a4edc6604c74817ce3") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.searchSubFieldDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd3d909edc6604c74817ce2"), "UserDetails" : { "UserEmailId" : "John123@gmail.com", "UserAge" : 21 } } { "_id" : ObjectId("5cd3d9a4edc6604c74817ce3"), "UserDetails" : { "UserEmailId" : "Carol@yahoo.com", "UserAge" : 26 } }
以下是在MongoDB上搜索子字段的查询-
> db.searchSubFieldDemo.find({"UserDetails.UserEmailId":"Carol@yahoo.com"});
这将产生以下输出-
{ "_id" : ObjectId("5cd3d9a4edc6604c74817ce3"), "UserDetails" : { "UserEmailId" : "Carol@yahoo.com", "UserAge" : 26 } }