How Do I Join Collections in MongoDB?

Question

Imagine you have a collection for posts, and each of these posts has the attribute userid: ObjectId( ), where ObjectID is referencing a document in the Users collection.

How would you go about retrieving the user information (in this case, the user document might contain a username, email, full name, etc) as part of a query on the Posts collection?

 

Answer

MongoDB does not support joins and so requires repeated queries over respectively over the two collections. It would be convenient if we could handle the join separately in a computing engine, such as Structured Process Language (SPL). Suppose I have two collections – employee and seller and need to find sales orders where the employee.state is California. The SPL script is as below:

A

1

=mongo_open(“mongo://localhost:27017/local?user=test&password=test”)  

2

>sales=mongo_shell(A1,”test38.find()”)  

3

>employee=mongo_shell(A1,”test39.find()”).switch(SELLERID,sales:EID)  

4

=A3.select(SELLERID.STATE==“California”)  

5

>mongo_close(A1)

 

A2: sales

undefined

A3: employee

undefined

A4: Get the eligible records where order 1 and order 3 belong to the employee 1 who comes from California.

undefined