内嵌对象数组按条件查询

yeluxing 2014-08-31 08:39:57
{"username":"bob","friends":[{"name":"luther","age":18},{"name":"alex",age:18},{"name":"babo",age:30},{"name":"landon","age":18},{"name":"reele","age":19}]}
什么命令可以查出job的所有age为18的friends,不是18的不显示

find("username":"bob","friends.age":18)这样是不行的,结果不是18也返回

请高手了解清楚我的问题哦,谢谢!

...全文
158 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yeluxing 2014-09-09
  • 打赏
  • 举报
回复
非常感谢M1CR0S0FT的回复,您的方法不错,但是无法将您的命令语句整合到我的node.js里
yeluxing 2014-09-09
  • 打赏
  • 举报
回复
db.yourcollection.aggregate( { $match : {"username" : "bob" } } , { $unwind : "$friends" },  { $match : {"friends.age" : 18 } }                         ) 性能怎么样?如果不好,我是不是得改collections结构,不可用内嵌documents?谢谢!
yihong2017 2014-09-09
  • 打赏
  • 举报
回复
如果你的需求只是找出某人年龄为X的朋友,性能应该不是问题。
yihong2017 2014-09-04
  • 打赏
  • 举报
回复
可以用$unwind试试

db.yourcollection.aggregate( { $match : {"username" : "bob" } } , { $unwind : "$friends" },  { $match : {"friends.age" : 18 } }                         )
M1CR0S0FT 2014-09-04
  • 打赏
  • 举报
回复
本身数据在同一个DOCUMENT,你当然不能直接用语句完成你的需求,你只能写MAP REDUCE去实现! 大概实现如下:

var mFunction=function(){ filterFriends=[]; this.friends.forEach(function(s){ if(s.age==18){ filterFriends.push(s); } }); emit(this._id,{friends:filterFriends}); }

var rFunction=function(key,values){ return values[0];}

db.runCommand({mapReduce:'t1',map:mFunction,reduce:rFunction,out:{inline:1},query:{"friends.age":18}})

1,798

社区成员

发帖
与我相关
我的任务
社区描述
MongoDB相关内容讨论区
社区管理员
  • MongoDB社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧