I have data in one MongoDb table that I need copied to another MongoDb table. The first table has a field with different elements (see examples below) which I know how to work with. The second table, however, has a field with an array that is itself made up of different elements. How do I reference the values in the array?
I've tried field.array[0].element and field.array.0.element, but neither of those work.
If there's anyone that could explain how to do this today, I'd appreciate it. The client wants this done by the end of the day. I'm stuck and am about ready to result to copying and pasting data. Thanks!
Here's table1. Notice that "won" is empty; I'm trying to fill it:
{
"_id" : ObjectId("5733835a836265135854b7dd"),
"won" : {
}
}
{
"_id" : ObjectId("5733835a836265135854b7de"),
"won" : {
}
}
{
"_id" : ObjectId("5733835a836265135854b7df"),
"won" : {
}
}
Here's table2. I'm trying to get to the values for the elements userId and screenName:
{
"_id" : ObjectId("5733835a836265135854b7dd"),
"auction": ObjectId("5733833a49841cdd4eb0eef5",
"lead" : {
"bid" : NumberInt(481),
"bidders" : [
{
"userId" : ObjectId("5514d167ac52b1df65e03b4d"),
"screenName" : "mdoed",
}
]
}
}
{
"_id" : ObjectId("5733835a836265135854b7de"),
"auction": ObjectId("5733833a49841cdd4eb0eef5",
"lead" : {
"bid" : NumberInt(481),
"bidders" : [
{
"userId" : ObjectId("5514d167ac52b1df65e03b4e"),
"screenName" : "mdoed",
}
]
}
}
{
"_id" : ObjectId("5733835a836265135854b7df"),
"auction": ObjectId("5733833a49841cdd4eb0eef5",
"lead" : {
"bid" : NumberInt(481),
"bidders" : [
{
"userId" : ObjectId("5514d167ac52b1df65e03b4f"),
"screenName" : "mdoed",
}
]
}
}
Here's what table1 should look like after the update:
{
"_id" : ObjectId("5733835a836265135854b7dd"),
"won" : {
"bid" : NumberInt(481),
"userId" : ObjectId("5514d167ac52b1df65e03b4d"),
"screenName" : "mdoed"
}
}
{
"_id" : ObjectId("5733835a836265135854b7de"),
"won" : {
"bid" : NumberInt(481),
"userId" : ObjectId("5514d167ac52b1df65e03b4e"),
"screenName" : "mdoed",
}
}
{
"_id" : ObjectId("5733835a836265135854b7df"),
"won" : {
"bid" : NumberInt(481),
"userId" : ObjectId("5514d167ac52b1df65e03b4f"),
"screenName" : "mdoed",
}
}
Here's the query I've tried:
var newActiveProperties = db.table2.find({"auction": ObjectId("5733833a49841cdd4eb0eef5")}).toArray();
newActiveProperties.forEach(function(doc) {
db.table1.update(
{ "_id": doc._id, },
{ "$set": { "won.bid": doc.lead.bid, "won.userId": doc.lead.bidders[0].userId, "won.screenName": doc.lead.bidders[0].screenName
}
},
{ multi: true }
);
});
I suspect that the syntax doc.lead.bidders[0].userId is wrong, but I'm not sure what the correct syntax is.