要为MongoDB数组插入特定索引,可以使用$push运算符。让我们创建包含文档的集合
>db.insertToSpecificIndexDemo.insertOne({"StudentName":"Larry","StudentSubjects":["MySQL","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d2562a629b87623db1b2c") } >db.insertToSpecificIndexDemo.insertOne({"StudentName":"Chris","StudentSubjects":["C++","C"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d2573a629b87623db1b2d") }
以下是查询以借助find()方法显示集合中的所有文档
> db.insertToSpecificIndexDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9d2562a629b87623db1b2c"), "StudentName" : "Larry", "StudentSubjects" : [ "MySQL", "Java" ] } { "_id" : ObjectId("5c9d2573a629b87623db1b2d"), "StudentName" : "Chris", "StudentSubjects" : [ "C++", "C" ] }
以下是在_id“ 5c9d2573a629b87623db1b2d”中插入到MongoDB数组的特定索引的查询
> db.insertToSpecificIndexDemo.update( ... { _id: ObjectId("5c9d2573a629b87623db1b2d")}, ... { $push: { ... StudentSubjects: { ... $each: [ {"CoreSubject": "MongoDB"} ], ... $position: 0 ... } ... }} ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们检查该值是否插入到特定位置。上面,我们给索引0表示在开头插入
> db.insertToSpecificIndexDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9d2562a629b87623db1b2c"), "StudentName" : "Larry", "StudentSubjects" : [ "MySQL", "Java" ] } { "_id" : ObjectId("5c9d2573a629b87623db1b2d"), "StudentName" : "Chris", "StudentSubjects" : [ { "CoreSubject" : "MongoDB" }, "C++", "C" ] }
查看示例输出,将“ CoreSubject”:“ MongoDB”插入到MongoDB数组的开头。