Mongodb 之 $elemMatch 作用

Mongodb 在当内嵌文档中数据过多时 $elemMatch 进行精确查询。

1. 创建文档添加测试数据

db.test.insert({
    "content": "...",
    "comments": [
        {
            "author": "joe",
            "score": 3,
            "comment": "nice post"
        },
        {
            "author": "mary",
            "score": 6,
            "comment": "terrible post"
        },
        {
            "author": "luy",
            "score": 9,
            "comment": "file post"
        }
    ]
});

2. 首先使用普通方法进行查询

db.test.find({"comments":{"author":"joe", "score":3, "comment":"nice post"}});

(C:\Users\87325\AppData\Roaming\Typora\typora-user-images\image-20210607095026883.png

使用这种方式可以查询出数据,但是对于查询条件的顺序和数量都有要求。

3. 将条件顺序进行调整

db.test.find({"comments":{"score":3, "author":"joe", "comment":"nice post"}});

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-awl3niAg-1623031773031)(C:\Users\87325\AppData\Roaming\Typora\typora-user-images\image-20210607095353862.png)]

调整顺序后没有查询出任何数据

4. 使用点的方式进行查询·

db.test.find({"comments.author":"joe", "comments.score":9});

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dbpjswAy-1623031773032)(C:\Users\87325\AppData\Roaming\Typora\typora-user-images\image-20210607095723835.png)]

可以查询出数据,但是对于·查询结果不够精准,这种方式只要内嵌文档中存在条件中的数据那么就可以查询出相关数据。

如 author为joe 在第一条数据中而 score 为9 则在第三条数据中。

5. 使用 $elemMatch 进行查询

5.1 条件正确的查询
db.test.find({"comments":{"$elemMatch":{"author":"joe", "score":3}}});

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MOAu73EV-1623031773033)(C:\Users\87325\AppData\Roaming\Typora\typora-user-images\image-20210607100317131.png)]

查询成功。

5.2. 修改查询条件
db.test.find({"comments":{"$elemMatch":{"author":"joe", "score":5}}});

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-75JwTDpH-1623031773034)(C:\Users\87325\AppData\Roaming\Typora\typora-user-images\image-20210607100447428.png)]

数据为空。因为在文档中没有author 为 joe 和score 为5 的数据。

使用$elemMatch 可以再内嵌文档中数据过多时进行精确查找,避免数据的不准确。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐