search

Home  >  Q&A  >  body text

数据库 - 如何用$elemMatch返回数组中多条数据

问题描述

{
    "_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}}})

经测试$elemMatch只能返回数组中的一个文档。

解决方案

使用聚合

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()


最终还是得到了需要的数据格式。感谢!!!

淡淡烟草味淡淡烟草味2754 days ago639

reply all(1)I'll reply

  • 世界只因有你

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

    Try using aggregate

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

    reply
    0
  • Cancelreply