热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

mongodb内嵌数组查询问题:如何限定返回与条件匹配的数组

往数据库表“users”中插入测试数据db.users.insertMany([{_id:NumberLong(1181675746),shard_qty:4,good

//往数据库表“users”中插入测试数据> db.users.insertMany([{"_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('users').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}]
}

//实际返回的数据:

{"_id" : NumberLong(1181675746),"favorite_shards" : [{"sid" : NumberLong(580),"favorite_dt" : ISODate("2015-06-26T04:13:06.405Z"),"is_attention" : true},{"sid" : NumberLong(579),"favorite_dt" : ISODate("2015-06-26T04:13:06.405Z"),"is_attention" : true},{"sid" : NumberLong(578),"favorite_dt" : ISODate("2015-06-26T04:13:06.405Z"),"is_attention" : true},{"sid" : NumberLong(577),"favorite_dt" : ISODate("2015-06-26T05:20:48.449Z"),"is_attention" : true}]
}

//二:正确的查询条件:实现的逻辑就是将原来的数组拆开,然后重组就好了。

> db.getCollection('users').aggregate([{"$match":{"_id":NumberLong(1181675746)}},{"$project":{"_id":1,"favorite_shards":1}},{"$unwind": "$favorite_shards"},{$match: {"favorite_shards.sid": {'$in':[NumberLong(577),NumberLong(578)]}}},{"$group": {"_id": "$_id", "favorite_shards": {"$push": "$favorite_shards"}}}]).pretty()

{"_id" : NumberLong(1181675746),
"favorite_shards" : [{"sid" : NumberLong(578),"favorite_dt" : ISODate("2015-06-26T04:13:06.405Z"),"is_attention" : true},{"sid" : NumberLong(577),"favorite_dt" : ISODate("2015-06-26T05:20:48.449Z"),"is_attention" : true}
]
}

 


推荐阅读
author-avatar
会唱歌的高跟鞋
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有