在 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
}
]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP