MongoDB: 将引用用作键并手工添加值?
如需手动添加值,请在 MongoDB 中使用 $push。让我们创建一个包含文档的集合 -
> db.demo585.insert({ ... firstName: 'John', ... lastName: 'Doe', ... SubjectName:"MongoDB", ... Marks: [59] ... }); WriteResult({ "nInserted" : 1 }) > db.demo585.insert({ ... firstName: 'Chris', ... lastName: 'Brown', ... SubjectName:"MySQL", ... Marks: [79] ... }); WriteResult({ "nInserted" : 1 })
在集合中显示所有文档,利用 find() 方法 -
> db.demo585.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e91fd80fd2d90c177b5bcc3"), "firstName" : "John", "lastName" : "Doe", "SubjectName" : "MongoDB", "Marks" : [ 59 ] } { "_id" : ObjectId("5e91fd81fd2d90c177b5bcc4"), "firstName" : "Chris", "lastName" : "Brown", "SubjectName" : "MySQL", "Marks" : [ 79 ] }
以下是将引用用作键并手动添加值所需的查询 -
> db.demo585.update({ ... firstName: 'John', ... lastName: 'Doe', ... SubjectName:"MongoDB", ... Marks: [59] ... }, ... { ... "$push": { ... "Marks": { ... "Value": 59, ... "Times": 3 ... } ... } ... } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在集合中显示所有文档,利用 find() 方法 -
> db.demo585.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e91fd80fd2d90c177b5bcc3"), "firstName" : "John", "lastName" : "Doe", "SubjectName" : "MongoDB", "Marks" : [ 59, { "Value" : 59, "Times" : 3 } ] } { "_id" : ObjectId("5e91fd81fd2d90c177b5bcc4"), "firstName" : "Chris", "lastName" : "Brown", "SubjectName" : "MySQL", "Marks" : [ 79 ] }
广告