在 MongoDB 中查詢嵌入式文件陣列並推送另一個文件陣列?
為此,請將 $push 與更新一同使用。讓我們建立一個包含文件的集合 -
> 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 } ] }
廣告