相关疑难解决方法(0)

仅检索MongoDB集合中对象数组中的查询元素

假设我的收藏中有以下文件:

{  
   "_id":ObjectId("562e7c594c12942f08fe4192"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"blue"
      },
      {  
         "shape":"circle",
         "color":"red"
      }
   ]
},
{  
   "_id":ObjectId("562e7c594c12942f08fe4193"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"black"
      },
      {  
         "shape":"circle",
         "color":"green"
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

查询:

db.test.find({"shapes.color": "red"}, {"shapes.color": 1})
Run Code Online (Sandbox Code Playgroud)

要么

db.test.find({shapes: {"$elemMatch": {color: "red"}}}, {"shapes.color": 1})
Run Code Online (Sandbox Code Playgroud)

返回匹配的文档(文档1),但始终包含所有数组项shapes:

{ "shapes": 
  [
    {"shape": "square", "color": "blue"},
    {"shape": "circle", "color": "red"}
  ] 
}
Run Code Online (Sandbox Code Playgroud)

但是,我想仅使用包含以下内容的数组来获取文档(文档1)color=red:

{ "shapes": 
  [
    {"shape": "circle", "color": "red"}
  ] 
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

projection mongodb mongodb-query aggregation-framework

356
推荐指数
11
解决办法
26万
查看次数

使用 $map 进行 MongoDB 嵌套数组搜索

我有包含嵌套数组的集合。我需要根据以下条件获取数据:

empId : 19107
address.country: "AUS"
group.primaryGroup.primary:"Y"
group.subGroup.primarySubGroup.primary : "Y"
Run Code Online (Sandbox Code Playgroud)

输入:

{
    "empId": "19107",
    "address": [
        {
            "street": "no.12 wilson street",
            "country":"AUS"
        },
        {
            "description": "No.32 watson street",
            "country":"CAN"
        }
    ],
    "mobile": 2387468238,
    "group": [
        {
            "groupId": 75227,
            "primaryGroup": [
                {
                    "primary": "Y"
                },
                {
                    "primary": "N"
                }
            ],
            "subGroup": [
                {
                    "subGroupId": 123,
                    "primarySubGroup": [
                        {
                            "primary": "Y"
                        },
                        {
                            "primary": "N"
                        }
                    ]
                },
                {
                    "subGroupId": 234,
                    "primarySubGroup": [
                        {
                            "primary": "N"
                        },
                        {
                            "primary": "Y"
                        }
                    ] …
Run Code Online (Sandbox Code Playgroud)

mongodb mongodb-query aggregation-framework spring-data-mongodb

2
推荐指数
1
解决办法
5210
查看次数