search

Home  >  Q&A  >  body text

Database - How to use $elemMatch to return multiple pieces of data in an array

Problem Description

{
    "_id" : ObjectId("582bc1b1421e46e4c14e2be8"),
    "date" : "2016-10-21",
    "path" : [
        {
            "url" : "http://m.xin.com/quanguo/sanling/yishen/?q=三菱翼神",
            "query" : "三菱翼神",
            "dttime" : "2016-10-21 12:41:36",
            "time_stamp" : 1477024896,
            "platform" : "m"
        },
        {
            "url" : "http://m.xin.com/quanguo/sanling/yishen/?q=三菱翼神",
            "query" : "三菱翼神",
            "dttime" : "2016-10-21 12:41:36",
            "time_stamp" : 1477024896,
            "platform" : "m"
        }
    ],
    "cid" : "ecabb21f-cb89-992f-79d9-b920427097bf"
}
db.dw_all_query_user_path.find({"path.query":/三菱/i},{"path":{"$elemMatch":{"query": /三菱/i}}})

After testing, $elemMatch can only return one document in the array.

Solution

Use Aggregation

db.dw_all_query_user_path.aggregate(
{
    $match:{
        "path.query":/奔驰/i
    }
},
{
    $unwind:'$path'
},
{
    $match:{
        'path.query':/奔驰/i
    }
},
{
    $group:{
        _id:'$_id',
        cid:{$first:'$cid'},
        date:{$first:'$date'},
        path:{$push:'$path'}
    }
}).pretty()


Finally got the required data format. grateful! ! !

淡淡烟草味淡淡烟草味2839 days ago679

reply all(1)I'll reply

  • 世界只因有你

    世界只因有你2017-05-02 09:25:11

    Try using aggregate

    http://stackoverflow.com/a/15...

    reply
    0
  • Cancelreply