仅返回在文档中搜索的嵌入式属性的最后一级 [英] return only the last level of the embedded property that is searched in a document

查看:63
本文介绍了仅返回在文档中搜索的嵌入式属性的最后一级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些文件.

db.test.find({"house.floor":1})



    db.test.insertMany([{
        "name":"homer",
        "house": {
            "floor": 1,
            "room": 
            {
                "bed": "bed_pink",
                "chair":"chair_pink"
            }
        }

    },
    {
        "name":"marge",
        "house": {
            "floor": 1,
            "room": 
            {
                "bed": "bed_blue",
                "chair":"chair_red"
            }
        }

    }]
    )    

     db.test.find({"house.room.bed":"bed_blue"})

我只想返回搜索的最后一级的值.在这种情况下:

I want to return only the value of the last level of my search. in this case:

            {
                "bed": "bed_blue",
                "chair":"chair_red"
            }

我得到的答案是整个文档,我想前进到查询的特定级别.我该怎么办?

the answer I get, is the whole document, I want to advance to a certain level of the query. how can I do it?

推荐答案

您可以将aggregate$match$project一起使用,如下所示:

You can use aggregate together with $match and $project for this as follows:

db.test.aggregate([
  {
    $match: {
      "house.room.bed": "bed_blue"
    }
  },
  {
    $project: {
      "_id": 0,
      "bed": "$house.room.bed",
      "chair": "$house.room.chair"
    }
  }
])

此外,您可以根据需要修改$project部分.

Further, you can modify the $project part as needed.

这是一个演示: https://mongoplayground.net/p/Fvll0LFIvQy

这篇关于仅返回在文档中搜索的嵌入式属性的最后一级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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