要通过id搜索数组,请使用position $运算符。要进行更新,请使用MongoDB中的UPDATE。让我们创建一个包含文档的集合-
> db.demo49.insertOne( ... { ... ... "Name": "David", ... "Details": [ ... { ... "_id": "D1234", ... "Subject":"MySQL" ... }, ... { ... "_id": "E234", ... "Subject":"Java" ... }, ... { ... "_id": "F456", ... "Subject":"Python" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e270a77cfb11e5c34d89902") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo49.find();
这将产生以下输出-
{ "_id" : ObjectId("5e270a77cfb11e5c34d89902"), "Name" : "David", "Details" : [ { "_id" : "D1234", "Subject" : "MySQL" }, { "_id" : "E234", "Subject" : "Java" }, { "_id" : "F456", "Subject" : "Python" } ] }
以下是在MongoDB集合中通过其ID搜索数组条目的查询-
> db.demo49.update( {"Details._id":"E234"}, ... {$set:{"Details.$.Subject":"MongoDB"}}, false, true ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo49.find();
这将产生以下输出-
{ "_id" : ObjectId("5e270a77cfb11e5c34d89902"), "Name" : "David", "Details" : [ { "_id" : "D1234", "Subject" : "MySQL" }, { "_id" : "E234", "Subject" : "MongoDB" }, { "_id" : "F456", "Subject" : "Python" } ] }