MongoDB:$elemMatch 和 $and 在数组中查找对象有什么区别? [英] MongoDB: what is the difference between $elemMatch and $and to find objects inside array?

查看:30
本文介绍了MongoDB:$elemMatch 和 $and 在数组中查找对象有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查询操作符$和

db.collection.find({$and: [{"array.field1": "someValue"}, {"array.field2": 3}]})

以及投影运算符的使用$elemMatch

db.collection.find({array: {$elemMatch: {field1: "someValue", field2: 3}}})

查找包含数组内的对象字段的文档?

to find documents which contain the object fields inside an array?

推荐答案

您的第一个查询将查找文档,其中数组至少包含一个字段 1= somevalue 的元素和至少一个字段 2=3 的元素.两个元素可以不同.第二个将检索数组至少有一个元素同时匹配两个条件的文档.这里有一个数据样本来解释:

Your first query will find documents, where array have at least one element with field1= somevalue and at least one element with field2=3. Both elements can be different. The second one will retrieve documents where array have at least one element matching the two conditions simultaneously. Here's a data sample to explain :

   {
    array: [
      {
        field1: 1,   
      },
      {
        field2: 2
      },
      {
        field1: 1,
        field2: 3
      },
    ]
  },
  {
    array: [
      {
        field1: 1,
        field2: 2
      },
      {
        field2: 3
      }
    ]
  },
  {
    array: [
      {
        field1: 1,
        field2: "other"
      },
      {
        field2: 2
      }
    ]
  }

第一次查询

db.collection.find({"array.field1": 1,"array.field2": 2})(等价到您的 $ 和语法)

db.collection.find({"array.field1": 1,"array.field2": 2}) (equivalent to your $and syntax)

将返回三个文件,

db.collection.find({array: {$elemMatch: {field1: 1, field2: 2}}})

db.collection.find({array: {$elemMatch: {field1: 1, field2: 2}}})

将仅返回第二个文档(唯一一个元素同时满足两个条件的文档)

will return only the second document (the only one having an element matching both criterias)

第一个查询的逻辑运算符是 OR,第二个是 AND,在数组元素级别.

EDIT : The logical operator of the first query is OR, for the second one it's AND, at level of array element.

这篇关于MongoDB:$elemMatch 和 $and 在数组中查找对象有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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