MongoDB get SubDocument

前端 未结 2 1871
粉色の甜心
粉色の甜心 2020-12-13 05:19

I would like to retrieve a sub document from a document in MongoDB. I have the following document:

{
    \"_id\" : \"10000\",
    \"password\" : \"password1         


        
相关标签:
2条回答
  • 2020-12-13 06:11

    You can do it with Aggregation Framework. Query will be something like :

    db.customer.aggregate([
        {$unwind : "$channels"},
        {$match : {"channels.id" : "10000-1"}},
        {$project : {_id : 0, 
                     id : "$channels.id", 
                     name : "$channels.name", 
                     enabled : "$channels.enabled"}}
    ])
    
    0 讨论(0)
  • 2020-12-13 06:17

    Using MongoDB 3.4.4 and newer, the aggregation framework offers a number of operators that you can use to return the desired subdocument.

    Consider running an aggregate pipeline that uses a single $replaceRoot stage to promote the filtered subdocument to the top-level and replace all other fields.

    Filtering the subdocument requires the $filter operator which selects a subset of an array to return based on the specified condition i.e. returns an array with only those elements that match the condition. You can then convert the single array element to a document by using the $arrayElemAt operator

    Overall running this aggregate operation will yield the desired result:

    db.customer.aggregate([
        { "$replaceRoot": { 
            "newRoot": {
                "$arrayElemAt": [
                    { "$filter": {
                       "input": "$channels",
                       "as": "channel",
                       "cond": { /* resolve to a boolean value and determine if an element should be included in the output array. */
                           "$eq": ["$$channel.id", "10000-1"]
                        } 
                    } },
                    0 /* the element at the specified array index */
                ]
            }
        } }
    ])
    

    Output

    {
        "id" : "10000-1",
        "name" : "cust1chan1",
        "enabled" : true
    }
    
    0 讨论(0)
提交回复
热议问题