在 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
      }
   ]
}

更新日期:15-May-2020

133 次浏览

Kickstart Your Career

完成课程认证

开始
广告
© . All rights reserved.