Mongodb选择字段以返回数组中的嵌入式文档 [英] Mongodb select field to return embedded document in array

查看:72
本文介绍了Mongodb选择字段以返回数组中的嵌入式文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下示例文档:

{
  "_id" : "2",
  "objects" : [{
      "_id" : "1",
      "name" : "embedded "
    },{
      "_id" : "2",
      "name" : "embedded "
    },{
      "_id" : "3",
      "name" : "embedded "
    }],
  "name" : "gloss2"
}

是否只能返回一个子文档?这样,我不必选择整个父对象,获取列表,也不需要遍历列表来获取有问题的对象.

Is it possible to return only one subdocument? That way I don't have to select the whole parent object, get the list, and loop through the list to get the object in question.

{
    "_id" : "2",
    "name" : "embedded"
}

推荐答案

是否只能返回一个子文档?

Is it possible to return only one subdocument?

是的,但不是您想要的方式.如果执行以下操作,则只会返回数组的第一个元素:

Yes, but not the way you want. If you do the following, you will only get back the first element of the array:

coll.find({_id:'2'}, { 'objects.0': 1})

但是,您真正想要的是类似于以下内容的东西:

However, what you really want is something that looks like the following:

coll.find({_id:'2', 'objects._id': '3'}, { 'objects.$' : 1})

当然,这在MongoDB中实际上不起作用.

Of course, that does not actually work in MongoDB.

查看您的其他问题,这是使用嵌入式对象"而不是数组"的原因之一对象".使用嵌入式对象",您可以执行以下操作:

Looking at your other question, this is one of the reasons to use the "embedded object" instead of the "array of objects". With "embedded object" you could do the following:

coll.find({_id:'2'}, {'objects.3': 1}) // where 3 is the id of the third object

这使您可以仅选择所需的嵌入式对象".

This lets you pick just the "embedded objects" you need.

这样,我不必选择整个父对象...

That way I don't have to select the whole parent object...

与MongoDB一起使用的是父文档总是被获取.查询返回顶级文档.这被烘焙到整个架构中.即使您只请求文档的一小部分,服务器仍然必须在将所请求的文档提供给您之前将整个文档加载到内存中.

The thing with MongoDB is that the parent document is always fetched. Queries return top-level documents. This is baked into the whole architecture. Even if you request just a slice of the document the server still has to load the entire document into memory before serving you the requested piece.

解决此问题的唯一方法可能是新的聚合框架,但是还没有进入稳定分支.

The only way around this may be the new Aggregation Framework, but that is not yet in the stable branch.

这篇关于Mongodb选择字段以返回数组中的嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆