如何从MongoDB数组中检索第一个和最后一个元素,并将其设置为不同的字段



我的收藏:

{
"_id" : ObjectId("60e46c1dfc320656ffc683b4"),
"name" : "A",
"name_test" : "a b c",
"arr" : [
"1",
"2",
"3"
]
}
{
"_id" : ObjectId("60e46c20fc320656ffc683b5"),
"name" : "B",
"name_test" : "B A",
"arr" : [
"a",
"b",
"c"
]
}
{
"_id" : ObjectId("60e46c26fc320656ffc683b6"),
"name" : "T1",
"number" : 1,
"name_test" : "T1",
"arr" : [
"t1",
"t2",
"t3"
]
}

我想用数组"的第一个最后元素来扩展字段;arr";,类似:

{
"_id" : ObjectId("60e46c26fc320656ffc683b6"),
"name" : "T1",
"number" : 1,
"name_test" : "T1",
"arr" : [
"t1",
"t2",
"t3"
],
"first": "t1",
"last": "t3"
}

我正在为Mongo:尝试这个命令

db.test_coll.update({}, 
[{ $set: 
{ first: { $arrayElemAt: [ "$arr", 0 ]}, 
last: { $arrayElemAt: [ "$arr", -1 ]} }
},
])

我也试过:

db.test_dups.updateMany({$where: "this.arr.length > 1"}, ...

但并不成功。我得到了下一个错误:

[thread1] Error: the update operation document must contain atomic operators :
DBCollection.prototype.updateMany@src/mongo/shell/crud_api.js:568:1

我该怎么做?也许使用PyMongo?


问题解决方案:我的mongo是3.2,大多数命令在那里都不起作用,所以我用PyMongo:解决了它

bulk = db.test.initialize_ordered_bulk_op()
cnt = 0
for profiles in db.test.find():
cnt += 1 

try:
bulk.find({'_id': profiles['_id']}).update({'$set': {
'f': profiles['arr'][0],
'l': profiles['arr'][-1]
}
})
if cnt % 1000000 == 0:
print("Exectuting", cnt)
bulk.execute()
bulk = db.test.initialize_ordered_bulk_op()
except:
print(profiles['_id'], " - Did not worked out")

try:
bulk.execute()
except:
print("Bulk is Empty")
  • $expr$gt检查arr长度应大于1
  • $first$last运算符从arr中选择元素
db.test_dups.updateMany(
{ $expr: { $gt: ["$arr", 1] } },
[{
$set: {
first: { $first: "$arr" },
last: { $last: "$arr" }
}
}]
)

游乐场


问题解决方案:我的mongo是3.2,大多数命令在那里都不起作用,所以我用PyMongo:解决了它

bulk = db.test.initialize_ordered_bulk_op()
cnt = 0
for profiles in db.test.find():
cnt += 1 

try:
bulk.find({'_id': profiles['_id']}).update({'$set': {
'f': profiles['arr'][0],
'l': profiles['arr'][-1]
}
})
if cnt % 1000000 == 0:
print("Exectuting", cnt)
bulk.execute()
bulk = db.test.initialize_ordered_bulk_op()
except:
print(profiles['_id'], " - Did not worked out")

try:
bulk.execute()
except:
print("Bulk is Empty")

最新更新