我在一个MongoDb表中有数据需要复制到另一个MongoDb表。第一个表有一个包含不同元素的字段(参见下面的示例),我知道如何使用它们。但是,第二个表有一个字段,该字段本身由不同的元素组成。如何引用数组中的值?
我已经尝试过field.array [0] .element和field.array.0.element,但这些都没有。
如果今天有人可以解释如何做到这一点,我会很感激。客户希望在一天结束时完成此操作。我陷入困境,准备好复制和粘贴数据。谢谢!
这是table1。注意“won”是空的;我想填补它:
{
"_id" : ObjectId("5733835a836265135854b7dd"),
"won" : {
}
}
{
"_id" : ObjectId("5733835a836265135854b7de"),
"won" : {
}
}
{
"_id" : ObjectId("5733835a836265135854b7df"),
"won" : {
}
}
这是表2。我正在尝试获取元素userId和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",
}
]
}
}
以下是更新后table1应该是什么样子:
{
"_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",
}
}
以下是我尝试的查询:
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 }
);
});
我怀疑doc.lead.bidders [0] .userId的语法错误,但我不确定正确的语法是什么。