如何在 MongoDB 中向对象中的数组插入一项?
若要将一项插入对象中已创建的数组中,请使用 MongoDB $push。让我们创建一个包含下列文档的集合 -
> db.demo449.insertOne(
... {
... details1: {
... details2: [{
... _id:new ObjectId(),
... Name:"Chris"
... }],
... details3: [{
... _id:new ObjectId(),
... Name:"David"
... }]
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e7a40e971f552a0ebb0a6e3")
}在 find() 方法的帮助下从集合中找出所有文档 -
> db.demo449.find();
这会产生以下输出 -
{ "_id" : ObjectId("5e7a40e971f552a0ebb0a6e3"), "details1" : { "details2" : [ { "_id" :
ObjectId("5e7a40e971f552a0ebb0a6e1"), "Name" : "Chris" } ], "details3" : [ { "_id" :
ObjectId("5e7a40e971f552a0ebb0a6e2"), "Name" : "David" } ] } }以下是将一项插入对象中数组中的查询 -
> db.demo449.update({_id:ObjectId("5e7a40e971f552a0ebb0a6e3")}, {$push: {
'details1.details2':{_id:ObjectId(),"Name":"Carol"}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }在 find() 方法的帮助下从集合中找出所有文档 -
> db.demo449.find();
这会产生以下输出 -
{ "_id" : ObjectId("5e7a40e971f552a0ebb0a6e3"), "details1" : { "details2" : [ { "_id" :
ObjectId("5e7a40e971f552a0ebb0a6e1"), "Name" : "Chris" }, { "_id" :
ObjectId("5e7a41a671f552a0ebb0a6e5"), "Name" : "Carol" } ], "details3" : [ { "_id" :
ObjectId("5e7a40e971f552a0ebb0a6e2"), "Name" : "David" } ] } }
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP