MongoDB - Filtering the content of an internal Array in a resultset

后端 未结 5 669
再見小時候
再見小時候 2021-02-01 08:19

I\'m new using MongoDB, and I don\'t know how to solve the next problem:

I have a collection of documents like this:

{
 \"URL\": \"www.stackoverflow.com\         


        
5条回答
  •  無奈伤痛
    2021-02-01 09:09

    You can use aggregation framework of MongoDB.

    If you have a doc in your collection like ;

    {
     "URL": "www.stackoverflow.com",
     "TAGS": [
             {"NAME": "question", "VOTES": 3},
             {"NAME": "answer", "VOTES": 5},
             {"NAME": "problem", "VOTES": 2}
             ]
    }
    

    and you want to filter some elements of the array out you can use the aggregation sample;

    db.sof_table.aggregate
    ([
    {$unwind:'$TAGS'}, 
    {$match:{'TAGS.NAME':{$in:['answer','question']}}},
    {$group:{_id:'$URL',TAGS:{$push:'$TAGS'}}}
    ])
    

    This will result;

    {
        "result" : [
            {
                "_id" : "www.stackoverflow.com",
                "TAGS" : [
                    {
                        "NAME" : "question",
                        "VOTES" : 3
                    },
                    {
                        "NAME" : "answer",
                        "VOTES" : 5
                    }
                ]
            }
        ],
        "ok" : 1
    }
    

    as your expected result.

提交回复
热议问题