Mongodb 之 $elemMatch 作用

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 可以再内嵌文档中数据过多时进行精确查找,避免数据的不准确。

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值