2016-04-21 52 views
1

我试图形成蒙戈分贝以下文档的查询:MongoDB的:在使用同一查询结果从查询同一文档

myMetaDataDoc document 
{ 
    _id: <objectId>, 
    tour: 
    { 
    tourId: "TOURID1", 
    stops: [{ 
     locationId: "LOC1", 
     stopId: "STOPID1", 
     ... 
    ],[ 
     locationId: "LOC2", 
     stopId: "STOPID2", 
    ]} 
    } 
    schedule:{ 
    stopSchedules: [{ 
     stopId: "STOPID1" 
     ... 
    },{ 
     stopId: "STOPID2" 
     ... 
    }] 
    } 
} 

基本上,我想所有在各自的调度信息站一个位置。我需要一个查询,以实现以下几点:

  1. 查询所有停止与位置(例如LOC1)
  2. 查询从1
  3. 回报有stops.stopId所有stopSchedules停止+时间表

我试过的是使用聚合,但不能得到stops.stopId用于相同的查询。这是我的尝试:

db.myMetaDataDoc.aggregate([ 
{$match : {'tour.stops.locationId':'LOC1'}}, // all tour stops with locationId as LOC1 
{$unwind : '$tour.stops'}, // break all stops 
{$match : {'tour.stops.locationId':'LOC1'} }, // all tour with only stops with locationId as LOC1 
{$unwind : '$schedule.stopSchedules'}, // break all stopschedules 
{$match : {'schedule.stopSchedules.stopsId' : {$in :<stopId array>}} } // missing array of stopId 
]) 

除去最后$比赛,我收到一个“tour.stops”的所有行和单“schedules.stopSchedules”。

{ "_id" : ObjectId("xx1"), "myMetaDataDoc" : {"tour" : { "tourId" : "TOURID1", "stops" : { "locationId" : "LOC1", "stopId" : "STOPID1"} } , "schedule" : { "stopSchedules" : { "stopId" : "STOPID1", ...}}}} 
{ "_id" : ObjectId("xx2"), "myMetaDataDoc" : {"tour" : { "tourId" : "TOURID1", "stops" : { "locationId" : "LOC1", "stopId" : "STOPID1"} } , "schedule" : { "stopSchedules" : { "stopId" : "STOPID2", ...}}}} 

从这组行我只需要那些stops.stopId等于schedules.stopSchedules.stopId的。看来聚合不喜欢$在哪里。我应该使用mapreduce()来代替吗?或服务器端脚本?

欣赏所有的建议。

回答

0

在尝试了一下聚合和$ eq运算符后,我想我已经接近我需要的东西了。我所做的是跳过最后一场比赛,并使用$ eq运算符在有效字段的所有行上使用组。我后来使用投影将其删除。

db.myMetaDataDoc.aggregate([ 
{$match : {'tour.stops.locationId':'LOC1'}}, // all tour stops with locationId as LOC1 
{$unwind : '$tour.stops'}, // break all stops 
{$match : {'tour.stops.locationId':'LOC1'} }, // all tour with only stops with locationId as LOC1 
{$unwind : '$schedule.stopSchedules'}, // break all stopschedules 
{$group : { 
    '_id': '$tour.tourId', 
    valid: {$first: {$cond: [{$eq: ['$tour.stops.stopId','$schedule.stopSchedules.stopId']}, '1', '0']}}, // validate row 
    stop : { $first: '$tour.stops'}, 
    schedule : {$first: '$schedule.stopSchedules'} 
{$match : {'valid':'1'} }, // skip invalid rows 
{ 
    $project: {   // remove valid field 
     _id: 1, 
     stop: 1, 
     schedule:1 
    } 
} 
]) 

我仍然对更好的解决方案开放。