$ elementMatch查询MongoDB中

问题描述:

我需要找到具有product.typeCode中的元素[ “800”, “200”, “400”]

{ 
    "_id": "[email protected]", 
    "_class": "com.mongodb.BasicDBObject", 
    "accounts": [{ 
     "number": "96398-00910620286__DISABILITY", 
     "product": { 
      "typeCode": "400", 
      "nameCode": "401" 
     }, 
     "dependents": [], 
     "_id": "[email protected]__DISABILITYDSB" 
    }, { 
     "number": "96398-00910620286__LIFECNV", 
     "product": { 
      "typeCode": "300", 
      "nameCode": "LIFECNV" 
     }, 
     "dependents": [], 
     "_id": "[email protected]" 
    }] 
} 

我写此查询,但它没有返回结果

find({ 
    accounts: { 
     $elemMatch: { 
      product: { 
       typeCode: { 
        $in: ["400"] 
       } 
      } 
     } 
    } 
}) 

请尝试以下查询。您可以在IN子句中添加附加值(800,200,400)。

db.collection.find({ "accounts.product.typeCode" : { 
        $in: ["400"] 
       } 
      } 
    ); 

与所有三个值: -

db.productlist.find({ "accounts.product.typeCode" : { 
        $in: ["400", "800", "200"] 
       } 
      } 
    );