How I can make a lookup without to overwrite the existing data.
I recreated the situation in mopngodb playground: mongo db playground example
The problem is that I need to lookup the events and all the object ids (subevents, tags).
But the problem starts on the first lookup to the subevents. I need to have all the lookup data on the same place like the id for the lookup. But the rest from the data from the event is gone only the subevents are there.
Any ideas?
as you are giving lookup output name same as existing field it overwrites existing data, if you give new name it persists all data.
for example below aggregation gives the main events and sub events details, if required we can use project stages to put subevents under main event:
[{$match: {
type: "EVENT"
}}, {$lookup: {
from: "events",
localField: "markedItemID",
foreignField: "_id",
as: "marked_event"
}}, {$unwind: {
path: "$marked_event"
}}, {$lookup: {
from: "events",
localField: "marked_event.baseData.subEvents",
foreignField: "_id",
as: "marked_subEvents"
}}]
https://mongoplayground.net/p/dlxqiK1PKdH
Related
I am having 2 collections -
Collection name is content
Collection name is surveys
I actually want to add the "type" information from the content collection to every content in every survey in the "surveys" collection.
I know in SQL we have to join these 2 tables first on _id and content_id commun columns and then add type column to suryeys table but not sure how should i do it here. I want the type value from content collection to add in every content field inside surveys collection. Please help me.
One option is:
Using $lookup to get the data from content collection
Merge the arrays using $mergeObjects and $indexOfArray. After the lookup, the content data is on someField array. This step finds the releant content from someField and put it inside the matching survey's content item, under the key type. This step also removes someField.
Format the result using $map. This step uses $map to iterate over the content array and format the data under type to contain only the wanted part.
Save it back using $merge. This step saves the result back into the collection.
db.surey.aggregate([
{$lookup: {
from: "content",
localField: "content.content_id",
foreignField: "_id",
as: "someField"
}},
{$set: {
someField: "$$REMOVE",
content: {$map: {
input: "$content",
in: {$mergeObjects: [
"$$this",
{type: {
$arrayElemAt: [
"$someField",
{$indexOfArray: ["$someField._id", "$$this.content_id"]}
]
}}
]}
}}
}},
{$set: {content: {$map: {
input: "$content",
in: {$mergeObjects: ["$$this", {type: "$$this.type.type"}]}
}}}},
{$merge: {into: "surey"}}
])
See how it works on the playground example
In mongoose (I assume you could be using mongoose, sind you added the tag) you can specify the relation in Schema definition and just just populate to add these fields to the output.
If you are not using mongoose you can use $lookup (https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/) in your aggregation pipeline.
{
from: "content",
localField: "content._id",
foreignField: "_id",
as: "someField"
}
I have a model that i want to get the user aggregate after some lookup during the login which I am thinking of adding to the mongoose hook below
schema.pre("find", async function (next) {
this.aggregate([
{$lookup: {from: "categories", localField: "categories", foreignField: "_id", as: "categories"}},
])
next();
});
But this does not have the aggregate method exposed at this point. What is the possible solution I can opt-in for ? I don't want to make a separate aggregate call or a different endpoint for just the aggregate
I have a users schema and a votes schema. I'm trying to return only users who haven't voted (have no returned votes).
I found this answer and using $lookup I have the below code to find each user and return all their votes as well. Which is halfway to what I'm trying to achieve.
How would I build a query so it only returns a user if they have no votes?
db.users.aggregate([
{
$addFields: { "_id": { "$toString": "$_id" } }
},
{
$lookup:
{
from: "votes",
localField: "_id",
foreignField: "voterId",
as: "votes"
}
}
])
Another question once I have a working solution, how would I go about scaling this up? Running this query in Robo 3T takes 9.05 seconds already for just loading 50 users and I have almost 40,000 users and over 200,000 votes in my database (which will only grow). Is there a more efficient way to do this? The final code will run on a Node.js server.
Update
As silencedogood said in a deleted answer, I don't need to use $addFields because user._id is automatically converted to a string (I thought it would be an ObjectId() initially). This however only saves 1 second off of loading 50 users (8.14s).
db.users.aggregate([
{
$lookup:
{
from: "votes",
localField: "_id",
foreignField: "voterId",
as: "votes"
}
}
])
I still need to figure out how to only return users who haven't voted.
An example shot of your data, and expected result, would help. The $addFields function is likely what is killing your performance. Why do you need this?
If the voterId is formatted as a string in the voter collection, but an objectId in the user collection (which I'm guessing is the case), you'll need to permanently cast to objectId if you want maximum performance. Nonetheless, this is roughly what you're looking for:
db.users.aggregate([
{
$lookup:
{
from: "votes",
localField: "_id",
foreignField: "voterId",
as: "votes"
}
},
{ "$match": { "votes.0": { "$exists": false } } }
])
This alone will only return users who don't have a vote entry. The equivalent of a left join, essentially.
Update
Since they are both strings, you can disregard that aspect of the answer. As to your performance issue... Not sure at the moment. That seems very unrealistic, I've never experienced query times that lengthy with a simple $lookup.
Iam working on the Go project and I am using mongodb to store my data. But suddenly the mongodb query execution took too much time to get data.
I have a collection named "cars" with around 25000 documents and each document containing around 200 fields (4.385KB). I have an aggregate query like this:
db.cars.aggregate([
{
$lookup:
{
from: "users",
localField: "uid",
foreignField: "_id",
as: "customer_info"
}
},{
$unwind: "$customer_info"
},{
$lookup:
{
from: "user_addresses",
localField: "uid",
foreignField: "_id",
as: "address"
}
},{
$unwind: "$address"
},{
$lookup:
{
from: "models",
localField: "_id",
foreignField: "car_id",
as: "model_info"
}
},{
$match:{
purchased_on:{$gt:1538392491},
status:{$in:[1,2,3,4]},
"customer_info.status":{$ne:9},
"model_info.status":{$ne:9},
}
},{
$sort:{
arrival_time:1
}
},{
$skip:0
},{
$limit:5
}
])
My document structure is like: https://drive.google.com/file/d/1hM-lPwvE45_213rQDYaYuYYbt3LRTgF0/view.
Now, If run this query with out indexing then it take around 10 mins to load the data. Can anyone suggest me how can I reduce its execution time ?
There are many things to do to optimize your query. What I would try :
As Anthony Winzlet said in comments, use as possible $match stage as first stage. This way, you can reduce number of documents passed to the following stages, and use indexes.
Assuming you use at least 3.6 mongo version, change your lookup stages using the 'let/pipeline' syntax (see here). This way, you can integrate your 'external filters' ( "customer_info.status":{$ne:9}, "model_info.status":{$ne:9} ) in a $match stage in your lookups pipeline. With indexes on right fields / collections, you will gain some time / memory in your $lookup stages.
Do your unwind stages as late as possible, to restrict number of documents passed to the following stages.
It's important to understand how works aggregation pipeline : each stage receive data, do its stuff, and pass data to next stage. So the less data is passed to the pipeline, the faster will be your query.
I have a collection (collectionA) that stores an event ID in an event array. The event array information comes from (collectionB).
Lately when an event is deleted from CollectionB via the web app, it sometimes does not get removed from Collection A as it should.
Is there a query i can do in mongo 3.0 to check to see what event_id's exist in CollectionA that are not in collectionB. Those will be the ones that need to be removed while the development team resolves the issue?
Here is a sample query that will give you list of such objects, assuming, collectionA has events array with IDs from collectionB
db.collectionA.aggregate([
{$unwind: '$events'},
{$lookup: {
from: 'collectionB',
localField: 'events',
foreignField: '_id',
as: 'event'
}},
{$unwind: {path: '$event', preserveNullAndEmptyArrays:true}},
{$match:{ 'event': {$exists:false}}},
])