0

数据:

[{        
                    "shop_ID" : "ABCD",
                    "plan" : 2,
                    "planType" : 2,
                    "goods_id" : "9612",
                    "category" : "1",
                    "keywords" : [
                        {
                            "keyword" : "lianyiqun",
                            "price" : 3.12,
                            "score" : 9
                        },
                        {
                            "keyword" : "nvzhuang",
                            "price" : 6.57,
                            "score" : 6
                        },
                        {
                            "keyword" : "chunzhuang",
                            "price" : 5.55,
                            "score" : 8
                        }
                    ]
                },
                {
                    "shop_ID" : "ABCD",
                    "plan" : 2,
                    "planType" : 2,
                    "goods_id" : "5078",
                    "category" : "1",
                    "keywords" : [
                        {
                            "keyword" : "lianyiqun",
                            "price" : 9.26,
                            "score" : 8
                        },
                        {
                            "keyword" : "nvzhuang",
                            "price" : 4.52,
                            "score" : 9
                        }
                    ]
                }]

我使用了命令查询:

db.test.find({"keywords" : { $elemMatch: {"score":{"$gte":8}} } })

结果不对,都是文件。

并且,使用命令 db.test.find({"keywords."score":{"$gte":8}})

结果是一样的。

我想要第一个文档的查询结果如下:

{        
                        "shop_ID" : "ABCD",
                        "plan" : 2,
                        "planType" : 2,
                        "goods_id" : "9612",
                        "category" : "1",
                        "keywords" : [
                            {
                                "keyword" : "lianyiqun",
                                "price" : 3.12,
                                "score" : 9
                            },
                            {
                                "keyword" : "chunzhuang",
                                "price" : 5.55,
                                "score" : 8
                            }
                        ]
                    },

如何查询内部文档?

4

1 回答 1

0

有一个$elemMatch投影运算符,它将从每个数组中返回一个与您的条件匹配的元素:

db.test.find( { } , 
              { keywords: { $elemMatch: { score: { $gte: 8 } } } } 
            )

要返回子文档中分数 >= 8 的所有元素,可以使用聚合框架

 db.test.aggregate ( [ { $unwind: "$keywords" },
                       { $match: { "keywords.score" : { $gte: 8 } } } 
                     ] )

问候

于 2013-03-23T16:19:50.347 回答