为此,请使用$push和update。让我们创建一个包含文档的集合-
> db.demo573.insertOne(
... {
... '_id' :101,
... 'SearchInformation' : [
... {
... 'Site' : 'Facebook.com',
... 'NumberOfHits' : 100
... },
... {
... 'Site' : 'Twitter.com',
... 'NumberOfHits' : 300
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo573.find();
这将产生以下输出-
{ "_id" : 101, "SearchInformation" : [ { "Site" : "Facebook.com", "NumberOfHits" : 100 }, { "Site" : "Twitter.com", "NumberOfHits" : 300 } ] }
以下是如何在MongoDB中查询嵌入式文档的数组-
> db.demo573.update({
... _id: 101,
... "SearchInformation.Site": {
... $nin: ["Google.com"]
... }
... }, {
... $push: {
... "SearchInformation": {
... 'Site' : 'Google.com',
... 'NumberOfHits' : 10000
... }
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo573.find().pretty();
这将产生以下输出-
{
"_id" : 101,
"SearchInformation" : [
{
"Site" : "Facebook.com",
"NumberOfHits" : 100
},
{
"Site" : "Twitter.com",
"NumberOfHits" : 300
},
{
"Site" : "Google.com",
"NumberOfHits" : 10000
}
]
}