Arrays versus Strings

When working through the quiz in M001 Chap3 one of the solutions changed the attribute type from array to string when it ended up having only one element.

How can we change the attribute back to array?

How would we know that the type had changed?

Hi!

What is the command run? Could you include a screenshot of the particular document?

An idea that comes to mind is this:

db.collection.updateOne(
{_id:ObjectId("<id>")},
{$set:{field:["newval"]}})

To search for the particular document by _id also using updateOne to be semantically consistent, and $set to set the field to a new value.

But there are presumably better options… maybe using Atlas or Compass.

Starting with this:

MongoDB Enterprise atlas-qu6b0r-shard-0:PRIMARY> db.pets.find().pretty()
{
        "_id" : ObjectId("5ec414e5e722bb1f65a25451"),
        "pet" : "wolf",
        "domestic?" : false,
        "diet" : "carnivorous",
        "climate" : [
                "polar",
                "equatorial",
                "continental",
                "mountain"
        ]
}
{
        "_id" : ObjectId("605f3ae4549c72555bba1d29"),
        "pet" : "cat",
        "domestic?" : false,
        "diet" : "carnivorous",
        "climate" : [
                "polar",
                "equatorial",
                "continental",
                "mountain"
        ]
}
MongoDB Enterprise atlas-qu6b0r-shard-0:PRIMARY>

Issuing command

db.pets.updateMany({ "pet": "cat" }, 
    { "$push": { "climate": "continental", "look": "adorable" } })

results in:

MongoDB Enterprise atlas-qu6b0r-shard-0:PRIMARY> db.pets.find().pretty()
{
        "_id" : ObjectId("5ec414e5e722bb1f65a25451"),
        "pet" : "wolf",
        "domestic?" : false,
        "diet" : "carnivorous",
        "climate" : [
                "polar",
                "equatorial",
                "continental",
                "mountain"
        ]
}
{
        "_id" : ObjectId("605f3ae4549c72555bba1d29"),
        "pet" : "cat",
        "domestic?" : false,
        "diet" : "carnivorous",
        "climate" : "continental"
}
MongoDB Enterprise atlas-qu6b0r-shard-0:PRIMARY>

climate for cat is now a string where climate for wolf is an array

$set can be used to reverse the effect.

If we test this code:

db.meow.insert({"climate":[1,2,3]})
db.meow.updateOne({ "$push": { "climate": "continental", "look": "adorable" } })
db.meow.find().pretty()
{
  "_id": ObjectId("605f6c8ca52c3e7ea4aaf5ad"),
  "climate": [
    1,
    2,
    3,
    "continental"
  ],
  "look": [
    "adorable"
  ]
}

Does this help?

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.