Aggregate documents where objects in array matches multiple conditions

后端 未结 1 431
轻奢々
轻奢々 2020-12-21 06:42

I have a collection with documents similar to such:

{
    \"_id\": ObjectId(\"xxxxx\"),
    \"item\": [
        { \"         


        
相关标签:
1条回答
  • 2020-12-21 07:03

    You can use the below query with $elemMatch to match the array's both values.

    Something like

    db.collection_name.aggregate({
      "$match": {
        "item": {
          "$elemMatch": {
            "property.0": "attr1",
            "property.1": /^\+/
          }
        }
      }
    });
    

    Also, you can use $all operator if you don't want to reference array index.

    db.collection_name.aggregate({
      "$match": {
        "item": {
          "$elemMatch": {
            "property": {
              "$all": [
                "attr1",
                /^\+/
              ]
            }
          }
        }
      }
    });
    
    0 讨论(0)
提交回复
热议问题