MongoDB 查询嵌入式文档字段 [英] MongoDB Query Embedded Document Field

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

问题描述

我的收藏结构如下图:

我正在尝试查询每个引擎中的字段名称":

I'm trying to query the field "name" inside every engine:

db.getCollection('scan').find({},
   {
        "engines": {
            "$elemMatch": {
                "name": 1
            }
        }
    }
)

但返回的结果只包含_id":

but the returning results contain only the "_id":

有人知道为什么吗?谢谢!

Does anyone know why? Thanks!

推荐答案

我正在尝试查询每个引擎中的字段名称":

I'm trying to query the field "name" inside every engine:

假设这个数据样本:

db.collection.insert([
  { engines: { ahnlab: { name: "x", value: "1" }}},
  { engines: { ahnlab: { name: "y", value: "2" }}},
])

您可以使用投影运算符中的点符号查询所有嵌入的字段name:

You can query all embedded fields name using the dot-notation in the projection operator:

> db.collection.find({},{"engines.ahnlab.name": 1, "_id":0 })
{ "engines" : { "ahnlab" : { "name" : "x" } } }
{ "engines" : { "ahnlab" : { "name" : "y" } } }

  • "engines.ahnlab.name": 1 将指示 MongoDB 保留 (1) 嵌入的名称字段;
  • "_id": 0 将指示 MongoDB 不要保留 _id 字段.
    • "engines.ahnlab.name": 1 will instruct MongoDB to keep (1) the embedded name field;
    • "_id": 0 will instruct MongoDB to not keep the _id field.
    • 如果您需要将输出作为平面数据结构,您应该使用聚合框架和 $project 操作符重写你的文档:

      If you need your output as a flat data structure, you should use the aggregation framework and the $project operator to rewrite your documents:

      > db.collection.aggregate([
          {$project: { name: "$engines.ahnlab.name", _id: 0 }}
      ])
      { "name" : "x" }
      { "name" : "y" }
      

      这篇关于MongoDB 查询嵌入式文档字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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