Andresse Njeungoue
Andresse Njeungoue

Reputation: 608

Pymongo select value on multiple collections where condition, and group by date

Am new in mongodb and I work using pymongo

Is there a way to select specific field in multiple collections where specific date matches query parameter, and group records by date?

Demonstration:

I have 2 collections A, B

A:

{
   "_id" : ObjectId("7d663451d1e7242c4b68ekjd"), 
   "date" : "Mon Dec 27 2010 18:51:00 GMT+0000 (UTC)", 
   "value" : 1, 
}
{
   "_id" : ObjectId("qd663451d1e7242c4b68e001"), 
   "date" : "Mon Dec 27 2010 18:52:00 GMT+0000 (UTC)", 
   "value" : 2, 
}
...
...

B:

{
   "_id" : ObjectId("td663451d1e7242c4b68eiu6"), 
   "date" : "Mon Dec 27 2010 18:51:00 GMT+0000 (UTC)", 
   "prediction_value" : 3, 
}
{
   "_id" : ObjectId("4d663451d1e7242c4b68e004"), 
   "date" : "Mon Dec 27 2010 18:52:00 GMT+0000 (UTC)", 
   "prediction_value" : 4, 
}
...
...

e.g:

If I search for date == Mon Dec 27 2010 18:52:00 GMT+0000 (UTC)

I need to get A.value and B.prediction_value and group records by this date

result like:

"Mon Dec 27 2010 18:52:00 GMT+0000": [ 
 { 
   "A" : 2
 },
 {
   "B" : 4
 }
]

I would greatly appreciate some example as I am a novice. Thank's for your comprehension.

Upvotes: 2

Views: 430

Answers (1)

sanyassh
sanyassh

Reputation: 8510

You can do two easy queries separately:

date = 'Mon Dec 27 2010 18:52:00 GMT+0000'
A_doc = db.A.find_one({'date': date})
B_doc = db.B.find_one({'date': date})
A_value = A_doc['value']
B_prediction_value = B_doc['prediction_value']
# manipulate the data as you want

Mongo doesn't have full support of multi-collection queries, only $lookup for left outer join. But I think that doing two simple queries is more preferable than one difficult, in most cases. Check this links for more info:

Search on multiple collections in MongoDB

MongoDB query multiple collections at once

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

Upvotes: 2

Related Questions