原数据为:
{
"_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
}
]
}
查询条件为
db.getCollection('web_mem_favorites').findOne(
{
'_id':NumberLong(1181675746),
'favorite_shards.sid': {
'$in':[NumberLong(577),NumberLong(578)]
}
}
,{"favorite_shards":1}
)
想返回的数据:
{
"_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. Use the following statement to return only the current matching array:
When the favorite_shards array is returned, only the second array element is returned.
But this requires knowing in advance which element sid:577 is.
In the mongodb array query manual, there is no method that can return array units that meet custom conditions. You can try to use a program to filter the favorites_shards data on the returned result set.
I understand the meaning of the question, here is the modified code
Result:
{ "_id" : NumberLong(1181675746), "favorite_shards" : [ { "sid" : NumberLong(578), "favorite_dt" : ISODate("2015-06-26T0406.405Z"), " is_attention" : true }, { "sid" : NumberLong(577), "favorite_dt" : ISODate("2015-06-26T0548.449Z"), "is_attention" : true } ] }
You can use the projection operator $elemMatch:
The limitation of $elemMatch is that it can only return the first matching record in the array.
I would like to ask what software this is?
You can use $unwind to query, and multiple subdocuments that meet the query conditions will be returned.