查询只返回嵌入式文档的 MongoDB
无法只返回嵌入式文档。但它将返回集合中的所有文档。让我们首先实现以下查询来创建具有文档的集合
>db.queryToEmbeddedDocument.insertOne({"UserName":"Larry","PostDetails":[{"UserMessage":"Hello","UserLikes":8},{"UserMessage":"Hi","UserLikes":6},{"UserMessage":"Good Morning","UserLikes":12},{"UserMessage":"Awesome","UserLikes":4}]}); { "acknowledged" : true, "insertedId" : ObjectId("5c988a9f330fd0aa0d2fe4bd") }
以下是用 find() 方法显示集合中所有文档的查询
> db.queryToEmbeddedDocument.find().pretty();
这将生成以下输出
{ "_id" : ObjectId("5c988a9f330fd0aa0d2fe4bd"), "UserName" : "Larry", "PostDetails" : [ { "UserMessage" : "Hello", "UserLikes" : 8 }, { "UserMessage" : "Hi", "UserLikes" : 6 }, { "UserMessage" : "Good Morning", "UserLikes" : 12 }, { "UserMessage" : "Awesome", "UserLikes" : 4 } ] }
以下是返回集合中所有文档的查询
> db.queryToEmbeddedDocument.find({"PostDetails.UserLikes": {$gte: 8}},{PostDetails:1}).pretty();
这将生成以下输出
{ "_id" : ObjectId("5c988a9f330fd0aa0d2fe4bd"), "PostDetails" : [ { "UserMessage" : "Hello", "UserLikes" : 8 }, { "UserMessage" : "Hi", "UserLikes" : 6 }, { "UserMessage" : "Good Morning", "UserLikes" : 12 }, { "UserMessage" : "Awesome", "UserLikes" : 4 } ] }
查看上面的示例输出,我们获得了所有文档,而我们只希望 UserLikes 大于或等于 8 的文档。
广告