栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

猫鼬-按条件查找子文档

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

猫鼬-按条件查找子文档

您可以

$elemMatch
在最新的MongoDB版本中用作查询投影运算符。从mongo shell:

db.parents.find(    {'children.age': {$gte: 18}},    {children:{$elemMatch:{age: {$gte: 18}}}})

这会从

children
数组中过滤掉较小的儿童文档:

{ "_id" : ..., "children" : [ { "name" : "Margaret", "age" : 20 } ] }{ "_id" : ..., "children" : [ { "name" : "John", "age" : 22 } ] }

如您所见,子代仍在其父文档中分组。MongoDB查询返回集合中的文档。您可以使用聚合框架的

$unwind
方法将它们拆分为单独的文档:

> db.parents.aggregate({    $match: {'children.age': {$gte: 18}}}, {    $unwind: '$children'}, {    $match: {'children.age': {$gte: 18}}}, {    $project: {        name: '$children.name',        age:'$children.age'    }}){    "result" : [        { "_id" : ObjectId("51a7bf04dacca8ba98434eb5"), "name" : "Margaret", "age" : 20        },        { "_id" : ObjectId("51a7bf04dacca8ba98434eb6"), "name" : "John", "age" : 22        }    ],    "ok" : 1}

我重复该

$match
条款的目的是:第一次通过该条款消除了 没有 18岁以上
育子女的父母,因此
$unwind
唯一考虑有用的文件。第二个
$match
删除
$unwind
不匹配的输出,并将
$project
子文档中的孩子的信息提升到顶层。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/385419.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号