MongoDB: what is the difference between $elemMatch and $and to find objects inside array?

前端 未结 2 674
不思量自难忘°
不思量自难忘° 2021-01-24 01:15

Is there any logical difference between the usage of the query operator $and

db.collection.find({$and: [{\"array.field1\": \"someValue\"}, {\"array.         


        
2条回答
  •  一个人的身影
    2021-01-24 02:12

    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
          }
        ]
      }
    

    The first query

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

    will returne the three documents,

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

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

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

提交回复
热议问题