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

  mongodb, question

Problem description

  • Server environment: mongo server version 3.0.10

  • Content format:

{
 "_id" : ObjectId("582bc1b1421e46e4c14e2be8"),
 "date" : "2016-10-21",
 "path" : [
 {
 "url" : "http://m.xin.com/quanguo/sanling/yishen/?  Q= mitsubishi wing god ",
 "query": "Mitsubishi Wing God",
 "dttime" : "2016-10-21 12:41:36",
 "time_stamp" : 1477024896,
 "platform" : "m"
 },
 {
 "url" : "http://m.xin.com/quanguo/sanling/yishen/?  Q= mitsubishi wing god ",
 "query": "Mitsubishi Wing God",
 "dttime" : "2016-10-21 12:41:36",
 "time_stamp" : 1477024896,
 "platform" : "m"
 }
 ],
 "cid" : "ecabb21f-cb89-992f-79d9-b920427097bf"
 }
  • Query statement:

Db.dw _ all _ query _ user _ path.find ({"path.query":/mitsubishi/i}, {"path": {"$ elemmatch": {"query":/mitsubishi /i}}}})

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

  • How can all the data in path array be returned?

Solution

Use aggregation

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

Finally, the required data format was obtained. Thank you! ! !

Try using aggregate

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