mongodbHow to do joins in MongoDB?
MongoDB supports various types of joins to combine documents from multiple collections. The most commonly used join is the $lookup
operator. It performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing.
db.collection.aggregate([
{
$lookup:
{
from: "otherCollection",
localField: "field1",
foreignField: "field2",
as: "alias_name"
}
}
])
The above example code performs a $lookup
operation on the collection
collection, joining documents from the otherCollection
collection. The localField
and foreignField
parameters specify the fields used to match documents from the two collections. The as
parameter specifies the name of the new array field in the input documents.
Other join operations supported by MongoDB include $merge
, $graphLookup
, $facet
, and $unwind
.
Helpful links
More of Mongodb
- How to list MongoDB users?
- How to query with "not equal" condition in MongoDB?
- How to empty an array in MongoDB?
- How to specify a password for MongoDB Docker?
- How to use watch in MongoDB?
- How to remove a field from MongoDB?
- How to use regex in MongoDB?
- How to use MongoDB query with "or" condition?
- How to create a many to many relation in MongoDB?
- How to kill an operation in MongoDB?
See more codes...