Mongodb Inline Array Query Question: How to Limit Returns of Arrays Matching Conditions

  mongodb, question

图片描述

The original data are:

{
 "_id" : NumberLong(1181675746),
 "shard_qty" : 4,
 "goods_qty" : 0,
 "shop_qty" : 0,
 "favorite_qty" : 4,
 "favorite_shards" : [
 {
 "sid" : NumberLong(580),
 "favorite_dt" : ISODate("2015-06-26T12:13:06.405+08:00"),
 "is_attention" : true
 },
 {
 "sid" : NumberLong(579),
 "favorite_dt" : ISODate("2015-06-26T12:13:06.405+08:00"),
 "is_attention" : true
 },
 {
 "sid" : NumberLong(578),
 "favorite_dt" : ISODate("2015-06-26T12:13:06.405+08:00"),
 "is_attention" : true
 },
 {
 "sid" : NumberLong(577),
 "favorite_dt" : ISODate("2015-06-26T13:20:48.449+08:00"),
 "is_attention" : true
 }
 ]
 }

The query criteria are

db.getCollection('web_mem_favorites').findOne(
 {
 '_id':NumberLong(1181675746),
 'favorite_shards.sid': {
 '$in':[NumberLong(577),NumberLong(578)]
 }
 }
 ,{"favorite_shards":1}
 )

Data to return:

{
 "_id" : NumberLong(1181675746),
 "favorite_shards" : [
 {
 "sid" : NumberLong(578),
 "favorite_dt" : ISODate("2015-06-26T12:13:06.405+08:00"),
 "is_attention" : true
 },
 {
 "sid" : NumberLong(577),
 "favorite_dt" : ISODate("2015-06-26T13:20:48.449+08:00"),
 "is_attention" : true
 }
 ]
 }

This is simple, using the following statement can only return the current matching array:

db.getCollection('web_mem_favorites').find({"_id":NumberLong(1181675746),"favorite_shards.sid":NumberLong(577)},{"favorite_shards.$":1}).pretty()