duansengcha9114 2016-08-15 19:59
浏览 62

如何使用MGO聚合管道查找符合特定条件的所有嵌入式文档

Lets say I have the following data in a Groups collection in MongoDB

[
    {
        “Group”: {
            “_id”: 1,
            “Requests”: [
                {
                    “_id”:1,
                    “name”:”Request A”
                }.
                {
                    “_id”:2,
                    “name”:”Request B”
                }
            ]       
        }
    },
            {
        “Group”: {
            “_id”: 2,
            “Requests”: [
                {
                    “_id”:3,
                    “name”:”Request C”
                }.
                {
                    “_id”:4,
                    “name”:”Request D”
                }
            ]       
        }
    }

]

Also, lets say I have the following function

func GetRequests(requestIDs []string) (Request[] error){
        //NEED TO IMPLEMENT W/ MGO
}

Is there a way to use the aggregation pipeline (or not if its not needed) to return just a projection of the requests matching requestIDs?

For example

Sample input reflecting requestIds

[1,2,4]

Sample output from mgo aggregation/query

[
  {
    “_id”:1,
    “name”:”Request A”
  },
  {
    “_id”:2,
    “name”:”Request B”
  },
  {
    “_id”:4,
    “name”:”Request D”
  }
]
  • 写回答

1条回答 默认 最新

  • dongxianghui3709 2016-08-16 01:54
    关注

    Try this

    db.groups.aggregate([{$unwind : '$Requests'},
                         {$match: {'Requests._id' :{$in: [1,2,4]}}}, 
                         {$project : {_id : '$Requests._id',name:'$Requests.name'}}]);
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向