原資料為:
{
"_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
}
]
}
迷茫2017-04-27 09:04:20
這個簡單,使用下面的語句就可以只傳回目前符合的陣列:
db.getCollection('web_mem_favorites').find({"_id":NumberLong(1181675746),"favorite_shards.sid":NumberLong(577)},{"favorite_shards.$":1}).pretty()
PHP中文网2017-04-27 09:04:20
javascript
db.getCollection('web_mem_favorites').find( {'_id':NumberLong(1181675746)},favorite_shards.sid': {'$in':[NumberLong(577)]}} {"_id" : 1, "favorite_shards": "$slice[2,1]" } )
favorite_shards陣列在回傳時,只傳回第二個陣列元素。
不過這個要提前知道sid:577是第幾個元素。
在mongodb的數組查詢手冊中,並沒有發現能返回滿足自訂條件的數組單元的方法,可以嘗試用程式在返回的結果集上再過濾下favorites_shards資料。
淡淡烟草味2017-04-27 09:04:20
findOne( {'_id':NumberLong(1181675746),'favorite_shards.sid': {'$in':[NumberLong(577)]}} ,{"favorite_shards.$":1, "_id": 0} )
懂題主意思了,以下是修改後的程式碼
db.test.aggregate({"$unwind":"$favorite_shards"}, {"$match":{"favorite_shards.sid": {"$in": [NumberLong(578), NumberLong(577)]}}}, {"$group": {"_id": "$_id", "favorite_shards":{'$push': "$favorite_shards"}}})
結果:
{ "_id" : NumberLong(1181675746), "favorite_shards" : [ { "sid" : NumberLong(578), "favorite_dt" : ISODate("2015-06-26T045 is_attention" : true }, { "sid" : NumberLong(577), "favorite_dt" : ISODate("2015-06-26T0548.449Z"), "is_attattion" : truemm48.449Z"), "is_attattion" : truel.
阿神2017-04-27 09:04:20
可以用projection操作符$elemMatch:
javascript
db.test.find({'favorite_shards.sid': 577}, {favorite_shards:{$elemMatch:{sid:577 } } }).pretty() { "_id" : NumberLong(1181675746), "favorite_shards" : [ { "sid" : NumberLong(577), "favorite_dt" : ISODate("2015-06-26T05:20:48.449Z"), "is_attention" : true } ] }
$elemMatch的限制是只能傳回數組中的第一個匹配記錄。
習慣沉默2017-04-27 09:04:20
可以使用$unwind查詢,也會傳回多個符合查詢條件的子文檔。
db.web_mem_favorites.aggregate(
{"$project":{"favorite_shards":"$favorite_shards"}},
{"$unwind":"$favorite_shards"},
{"$match":{"favorite_shards.sid": NumberLong(577)}}
)