I have a document like below:
{
"_id" : ObjectId("54b60ee28115386561cda04b"),
"a b" : "{c:d}",
}
I need to update 'a b'.c to value 'e'. Tried query below
db.test.update({"_id" : ObjectId("54b60ee28115386561cda04b")}, {$set:{'a b.c':'e'}});
but get error:
LEFT_SUBFIELD only supports Object: a b not: 2
Any advice, please?
There is nothing wrong with having a space in a key name ( except it looks bad and not a good practice ). So you can modify a correctly formed document with no problem.
{
"_id" : ObjectId("54b60ee28115386561cda04b"),
"a b" : { "c": "d" }
}
And update:
db.test.update(
{ "_id": ObjectId("54b60ee28115386561cda04b") },
{ "$set": { "a b.c": "e" } }
);
But your problem here is that the content of "a b" is a string. So there is no "c" sub-property to access.
{
"_id" : ObjectId("54b60ee28115386561cda04b"),
"a b" : "{c:d}",
}
Correct the document to contain a nested object:
db.test.update(
{ "_id": ObjectId("54b60ee28115386561cda04b") },
{ "$set": { "a b": { "c": "e" } } }
);
Future updates will work properly then
Related
I have a document:
{
"Name": "Downhill 3",
"Apartments": [
{
"Yardage": 55.5,
"Owner": {
"name" : "Timothy",
"surname" : "Notclement",
"phone" : 555666777
}
},
{
"Yardage": 70,
"Owner": {
"name" : "Anya",
"surname" : "Joylor-Tay",
"phone" : 555111000
}
}
]
}
It represents "all" apartments at some street.
I want to delete one entry from Apartments array, let's say the one which is owned by Anya, by specifying it by something like this Apartments.Owner.name:"Anya".
How can I perform such an operation? I tried to $pull and to $unset, but nothing worked. Now I came across findAndModify (docs here) and possibility to use an aggregation pipeline in the update field, but can't really figure out how to form a query.
Mongo commands I tried:
db.ApartCollection.update( { "_id":ObjectId("example123") }, { $unset: { "Apartments.Owner.name" : "Anya" } } )
db.ApartCollection.update( { "_id":ObjectId("example123") }, { $unset: { Apartments: { "Owner.name" : "Anya" } } } )
db.ApartCollection.update( { "_id":ObjectId("example123") }, { $pull: { Apartments: { "Owner.name" : "Anya" } } } )
db.Dokumenty.update( { "_id":ObjectId("61881be8dd6d25184a3b6c3f") }, { $pull: { "Apartments.Owner.name": "Anya" } } )
^This one doesn't even ?compile? It returns error:
Cannot use the part (Owner) of (Apartments.Owner.name) to traverse the element ({Apartments:...blah blah
I have the following document structure in a MongoDB collection :
{
"A" : [ {
"B" : [ { ... } ]
} ]
}
I'd like to update this to :
{
"A" : [ {
"B" : [ { ... } ],
"x" : [],
"y" : { ... }
} ]
}
In other words, I want the "x" and "y" fields to be added to the first element of the "A" array without loosing "B".
Ok as there is only one object in A array you could simply do as below :
Sample Collection Data :
{
"_id" : ObjectId("5e7c3cadc16b5679b4aeec26"),
A:[
{
B: [{ abc: 1 }]
}
]
}
Query :
/** Insert new fields into 'A' array's first object by index 0 */
db.collection.updateOne(
{ "_id" : ObjectId("5e7c3f77c16b5679b4af4caf") },
{ $set: { "A.0.x": [] , "A.0.y" : {abcInY :1 }} }
)
Output :
{
"_id" : ObjectId("5e7c3cadc16b5679b4aeec26"),
"A" : [
{
"B" : [
{
"abc" : 1
}
],
"x" : [],
"y" : {
"abcInY" : 1.0
}
}
]
}
Or Using positional operator $ :
db.collection.updateOne(
{ _id: ObjectId("5e7c3cadc16b5679b4aeec26") , 'A': {$exists : true}},
{ $set: { "A.$.x": [] , "A.$.y" : {abcInY :1 }} }
)
Note : Result will be the same, but functionally when positional operator is used fields x & y are inserted to first object of A array only when A field exists in that documents, if not this positional query would not insert anything (Optionally you can check A is an array condition as well if needed). But when you do updates using index 0 as like in first query if A doesn't exist in document then update would create an A field which is an object & insert fields inside it (Which might cause data inconsistency across docs with two types of A field) - Check below result of 1st query when A doesn't exists.
{
"_id" : ObjectId("5e7c3f77c16b5679b4af4caf"),
"noA" : 1,
"A" : {
"0" : {
"x" : [],
"y" : {
"abcInY" : 1.0
}
}
}
}
However, I think I was able to get anothe#whoami Thanks for the suggestion, I think your first solution should work. However, I think I was able to get another solution to this though I'm not sure if its better or worse (performance wise?) than what you have here. My solution is:
db.coll.update( { "_id" : ObjectId("5e7c4eb3a74cce7fd94a3fe7") }, [ { "$addFields" : { "A" : { "x" : [ 1, 2, 3 ], "y" : { "abc" } } } } ] )
The issue with this is that if "A" has more than one array entry then this will update all elements under "A" which is not something I want. Just out of curiosity is there a way of limiting this solution to only the first entry in "A"?
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.
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.
Can you try this please :
db.myPlaces.update(
{
name: "Place Q"
},{
$set:
{
image: db.myPlaces.find( { "images.0" } )
}
}
)
Here what you can do is:
Find the document first.
Iterate on that (You must have only one value, but it will work for multiple documents as well)
Update document.
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"
}
In MongoDB, I'm trying to write a query to add elements from an array to an existing document, but instead of adding the elements as objects:
property: ObjectID(xxx)
the elements are getting added as just
ObjectID(xxx)
Forgive me if I get the terminology wrong. I'm completely new to MongoDB; I normally only work with relational databases. How do I properly add these new elements?
I have a collection called auctions which has two fields: ID and properties. Properties is an array of objects named property. Here's an example with two auction documents:
** I changed the object IDs to make them easier to reference in our discussion
Collection db.auctions
{
"_id" : ObjectId("abc"),
"properties" : [
{
"property" : ObjectId("prop1")
},
{
"property" : ObjectId("prop2")
},
{
"property" : ObjectId("prop3")
}]
}
{
"_id" : ObjectId("def"),
"properties" : [
{
"property" : ObjectId("prop97")
},
{
"property" : ObjectId("prop98")
}]
}
I want to add 3 new properties to auction "abc". How do I do this?
Here's is what I tried:
I have an array of properties that looks like this:
Array PropsToAdd
[
ObjectId("prop4"),
ObjectId("prop5"),
ObjectId("prop6")
]
I wrote an update query to push these properties into the properties array in auctions:
db.auctions.update(
{"_id": "abc"}
,
{ $push: { properties: { $each: PropsToAdd } } }
);
This query gave the result below. Notice that instead of adding elements named property with a value from my array, it's just added my values from my array. I obviously need to add that "property" part, but how do I do that?
Collection db.auctions (_id "abc" only)
{
"_id" : ObjectId("abc"),
"properties" : [
{
"property" : ObjectId("prop1")
},
{
"property" : ObjectId("prop2")
},
{
"property" : ObjectId("prop3")
},
ObjectId("prop4"),
ObjectId("prop5"),
ObjectId("prop6"),
ObjectId("prop7")]
}
The result I'm looking for is this:
Collection db.auctions (_id "abc" only)
{
"_id" : ObjectId("abc"),
"properties" : [
{
"property" : ObjectId("prop1")
},
{
"property" : ObjectId("prop2")
},
{
"property" : ObjectId("prop3")
},
{
"property" : ObjectId("prop4")
},
{
"property" : ObjectId("prop5")
},
{
"property" : ObjectId("prop6")
}
}
Here is some further information on that array of properties I'm adding. I get it from running these queries. Perhaps one of them needs changed?
This query gets an array of current properties:
var oldActiveProperties = db.properties.distinct( "saleNumber", { "active": true, "auction": ObjectId("abc") } );
Then those results are used to find properties in the new file that weren't in the old file:
var PropsToAdd = db.newProperties.distinct(
"_id"
, { "saleNumber": { "$nin": oldActiveProperties }, "active": true}
);
The resulting array is what I need to add to the auctions collection.
Use the JavaScript's native map() method to map the array into an array of documents. The following shows this:
var PropsToAdd = db.newProperties.distinct("_id",
{ "saleNumber": { "$nin": oldActiveProperties }, "active": true}
).map(function (p) { return { property: p }; });
db.auctions.update(
{"_id": "abc"},
{ $push: { "properties": { "$each": PropsToAdd } } }
);
Past answers (from mid 2013 and before) don't seem to work and links to the documentation are all out of date.
Example user object:
{
"name": "Joe Bloggs",
"email": "joebloggs#example.com",
"workstations" : [
{ "number" : "10001",
"nickname" : "home" },
{ "number" : "10002",
"nickname" : "work" },
{ "number" : "10003",
"nickname" : "vacation" }
]
}
How can I modify the nickname of a workstation?
I tried using $set, workstations.$ and workstations.nickname but none gave the desired results.
Short answer, you have to use array index. For example, you want to update the nickname of 10002: {$set:{"workstations.1.nickname":"newnickname"}}
Here is the complete example:
> db.test.update({"_id" : ObjectId("5332b7cf4761549fb7e1e72f")},{$set:{"workstations.1.nickname":"newnickname"}})
> db.test.findOne()
{
"_id" : ObjectId("5332b7cf4761549fb7e1e72f"),
"email" : "joebloggs#example.com",
"name" : "Joe Bloggs",
"workstations" : [
{
"number" : "10001",
"nickname" : "home"
},
{
"nickname" : "newnickname",
"number" : "10002"
},
{
"number" : "10003",
"nickname" : "vacation"
}
]
}
>
If you don't know the index (position of the workstations), you can update the doc using $elemMatch:
>db.test.update(
{
"email": "joebloggs#example.com",
"workstations": { "$elemMatch" { "number" : "10002" } }
},
{
"$set": { "workstations.$.nickname": "newnickname2" }
}
)
>
#naimdjon's answer would work. To generalize, you could use the $elemMatch operator in combination with the $ positional operator to update one element in the array using below query:
db.test.update({
// Find the document where name="Joe Bloggs" and the element in the workstations array where number = "10002"
"name": "Joe Bloggs",
"workstations":{$elemMatch:{"number":"10002"}}
},
{
// Update the nickname in the element matched
$set:{"workstations.$.nickname":"newnickname"}
})
Note: $elemMatch is only required if you need to match more than one component in the array. If you are going to match on just the number, you could use "workstations.number":"10002"
As long as you know "which" entry you wish to update then the positional $ operator can be of help. But you need to update your query form:
db.collection.update(
{
"email": "joebloggs#example.com",
"workstations": { "$elemMatch" { "nickname" : "work" } }
},
{
"$set": { "workstations.$.nickname": "new name" }
}
)
So that is the general form. What you need to do here is "match" something in the array in order to get a "position" to use for the update.
Alternately, where you know the position, then you can just "specify" the position with "dot notation":
db.collection.update(
{
"email": "joebloggs#example.com",
},
{
"$set": { "workstations.1.nickname": "new name" }
}
)
Which updates the second element in the array, and does not need the "matching" part in the query.