Retrieve field value from array of sub document

后端 未结 2 1342
刺人心
刺人心 2021-01-25 22:12

I have some documents like this:

{
  \"hash\": \"14a076f9f6cecfc58339330eeb492e267f63062f6d5f669c7cdbfecf9eb4de32\",
  \"started_services\": [],
  \"deleted_file         


        
相关标签:
2条回答
  • 2021-01-25 22:49
    db.key.aggregate((
    { "$match": { 
            "datetime_int": { "$gte": 1451952000 }
            }},
    {"$unwind":"$software.adobe.licenses"},
    {"$project":{"key":"$software.adobe.licenses.key", "hash":1, "_id":0}}
    ))
    

    outputs the following :

    { "hash" : "14a076f9f6cecfc58339330eeb492e267f63062f6d5f669c7cdbfecf9eb4de32", "key" : [ "2384723", "23888823" ] }
    
    0 讨论(0)
  • 2021-01-25 23:00

    You can do this with the aggregation framework.

    db.repository.aggregate([ 
        { "$match": { 
            "datetime_int": { "$gte": 1451952000 }, 
            "software.adobe.licenses.key" : { "$exists" : true } 
        }}, 
        { "$project": { 
            "hash": 1, 
            "key": { 
                "$map": { 
                    "input": "$software.adobe.licenses", 
                    "as": "soft", 
                    "in": "$$soft.key"
                }
            }
        }}
    ])
    

    Starting From MongoDB 3.2 you can directly project the sub-document array field.

    { "$project": { "hash": 1, "key": "$software.adobe.licenses.key"}}
    
    0 讨论(0)
提交回复
热议问题