Reputation: 311
For a given document, I am attempting to set a field (string) as the first element of an array of strings. Consider a collection myPlaces
with the following document:
{
"name" : "Place Q",
"images" : [
"foo-1",
"foo-2",
"foo-3"
]
}
I am looking to create the following:
{
"name" : "Place Q",
"images" : [
"foo-1",
"foo-2",
"foo-3"
],
"image" : "foo-1"
}
So in the mongo shell, I execute:
db.myPlaces.update(
{
name: "Place Q"
},
{
$set:
{
image: images.0
}
}
)
This throws the error SyntaxError: missing } after property list
which I don't understand. If I enclose the array in quotes "images.0"
the value of image
is set as "images.0"
, not "foo-1"
.
I've been reviewing the Mongodb documentation and see a lot of different examples but not something that makes clear to me what is probably a simple syntax for accessing an array value.
Upvotes: 0
Views: 1034
Reputation: 4200
Here what you can do is:
Note:- Efficient for the small records. Bulk record will have lots of traffic on DB.
===== Will work for all version of MongoDB ======
Data Before:
{
"_id" : ObjectId("5d53fda5f5fc3d6486b42fec"),
"name" : "Place Q",
"images" : [
"foo-1",
"foo-2",
"foo-3"
]
}
Query:
db.collection.find({ name: "Place Q" }).forEach(function(document) {
db.collection.update(
{},
{ "$set": { "image": document.images[0] } }
);
})
Data After
{
"_id" : ObjectId("5d53fda5f5fc3d6486b42fec"),
"name" : "Place Q",
"images" : [
"foo-1",
"foo-2",
"foo-3"
],
"image" : "foo-1"
}
Upvotes: 0
Reputation: 442
Can you try this please :
db.myPlaces.update(
{
name: "Place Q"
},{
$set:
{
image: db.myPlaces.find( { "images.0" } )
}
}
)
Upvotes: 0
Reputation: 961
The following query works on MongoDB 4.2, It might not work on previous versions.
db.myPlaces.update(
{
name: "Place Q"
},
[
{
$set: {
image: {
$arrayElemAt: ["$images",0]
}
}
}
]
)
It's also very efficient as it is using $set pipeline provided in MongoDB 4.2+ versions.
Upvotes: 4