如何在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" } ] } }热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短