要将嵌入式对象作为文档检索,请使用聚合$replaceRoot。首先让我们创建一个包含文档的集合-
> db.embeddedObjectDemo.insertOne( { _id: new ObjectId(), "UserDetails": { "UserName": "John", "UserAge": 24, "UserEmailId": "John22@gmail.com" } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ced580fef71edecf6a1f693") } > db.embeddedObjectDemo.insertOne( { _id: new ObjectId(), "UserDetails": { "UserName": "Carol", "UserAge": 26, "UserEmailId": "Carol123@gmail.com" } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ced5828ef71edecf6a1f694") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.embeddedObjectDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ced580fef71edecf6a1f693"), "UserDetails" : { "UserName" : "John", "UserAge" : 24, "UserEmailId" : "John22@gmail.com" } } { "_id" : ObjectId("5ced5828ef71edecf6a1f694"), "UserDetails" : { "UserName" : "Carol", "UserAge" : 26, "UserEmailId" : "Carol123@gmail.com" } }
以下是通过MongoDB中的聚合框架将嵌入式对象作为文档检索的查询-
> db.embeddedObjectDemo.aggregate( [ { $replaceRoot: { newRoot: "$UserDetails" } } ] );
这将产生以下输出-
{ "UserName" : "John", "UserAge" : 24, "UserEmailId" : "John22@gmail.com" } { "UserName" : "Carol", "UserAge" : 26, "UserEmailId" : "Carol123@gmail.com" }