mongo实现子文档的任意查询

前端之家收集整理的这篇文章主要介绍了mongo实现子文档的任意查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

对于子文档的查询,通常可以根据$slice获取子集,但是这个子集是连续的,如果想要任意数量的符合条件的子文档,可以使用如下的方法

  1. db.test3.find().pretty()
  2. {
  3. "_id" : NumberLong(1181675746),"shard_qty" : 4,"goods_qty" : 0,"shop_qty" : 0,"favorite_qty" : 4,"favorite_shards" : [
  4. {
  5. "sid" : NumberLong(580),"favorite_dt" : ISODate("2015-06-26T04:13:06.405Z"),"is_attention" : true
  6. },{
  7. "sid" : NumberLong(579),{
  8. "sid" : NumberLong(578),{
  9. "sid" : NumberLong(577),"favorite_dt" : ISODate("2015-06-26T05:20:48.449Z"),"is_attention" : true
  10. }
  11. ]
  12. }
  13. > db.test3.aggregate([
  14. ... {"$match":{"_id":NumberLong(1181675746)}},... {"$project":{"_id":1,"favorite_shards":1}},... {"$unwind": "$favorite_shards"},//将数组拆开
  15. ... {$match: {"favorite_shards.sid": {'$in':[NumberLong(577),NumberLong(578)]}}},//找到满足条件的文档
  16. ... {"$group": {"_id": "$_id","favorite_shards": {"$push": "$favorite_shards"}}} //重组符合条件的文档构造新的数组
  17. ... ]).pretty()
  18. {
  19. "_id" : NumberLong(1181675746),"favorite_shards" : [
  20. {
  21. "sid" : NumberLong(578),"is_attention" : true
  22. }
  23. ]
  24. }

这样就可以达到我们的需求。

猜你在找的程序笔记相关文章