MongoDB 中的文档由字段和值对组成。您通常有一个_id
场与ObjectID用于标识文档和保存文档数据的附加字段的值,例如:
doc = {
_id: BSON::ObjectId('650aeca18772677bb6613a89'),
name: "foo"
}
然后可以通过以下方式将上述文档插入到集合中insert_one https://www.mongodb.com/docs/ruby-driver/current/api/Mongo/Collection.html#insert_one-instance_method:
coll.insert_one(doc)
这同样适用于嵌入数据,例如一个array called data
:
doc = {
_id: BSON::ObjectId('650aee198772677bb6613a8a'),
data: [
{ name: 'foo' },
{ name: 'bar' }
]
}
coll.insert_one(doc)
要将新值附加到现有数组,请执行以下操作$push https://www.mongodb.com/docs/manual/reference/operator/update/push/操作员:
coll.update_one(
{ _id: BSON::ObjectId('650aee198772677bb6613a8a') },
{ '$push': { data: { name: 'baz' } } }
)
To 将多个值附加到数组 https://www.mongodb.com/docs/manual/reference/operator/update/push/#append-multiple-values-to-an-array, 您可以使用$push
与$each
修饰符:
coll.update_one(
{ _id: BSON::ObjectId('650aee198772677bb6613a8a') },
{ '$push': { data: { '$each': [ { name: 'qux' }, { name: 'quux' } ] } } }
)
上述修改后的文档:
coll.find(_id: BSON::ObjectId('650aee198772677bb6613a8a')).first
#=> {
# "_id"=>BSON::ObjectId('650aee198772677bb6613a8a'),
# "data"=>[
# {"name"=>"foo"},
# {"name"=>"bar"},
# {"name"=>"baz"},
# {"name"=>"qux"},
# {"name"=>"quux"}
# ]
# }