Mongodb embed structure updating and searching?

安稳与你 提交于 2019-12-13 00:27:47

问题


Playing with MongoDB to store results from a nmap network scan, and trying to figure out the best way to structure the data.

At the moment I have the following :

{
    "_id" : ObjectId("525f94097025166583e18eba"),
    "ip" : "127.0.0.1",
    "services" : [ 
        {
            "port" : "22",
            "port_info" : [ 
                {
                    "product" : "ssh",
                    "version" : "1.0"
                }
            ]
        }, 
        {
            "port" : "80",
            "port_info" : [ 
                {
                    "product" : "apache",
                    "version" : "2.0"
                }
            ]
        }
    ]
}

I can find for example hosts with port 22 open, example against just 127.0.0.1 with this

db.hosts.find({ ip : "127.0.0.1"}, {"services" : { $elemMatch : { port : "22" }}})

But I am not sure, how to find for example all hosts, which has "product" : "ssh" try does, but I get a syntax error

db.hosts.find({ ip : "127.0.0.1"}, { services.port_info : { $elemMatch : { product : "ssh"    }}})

Then let's say I want to add another element to "port_info" maybe something like protocol : tcp

how would I do a update, where I say something like update where ip : 127.0.0.1 and product is ssh?


回答1:


  1. The syntax error is because you have to use quotes around services.port_info
  2. However, $elemMatch in nested fields is currently unsupported anyway
  3. Fortunately, you don't need $elemMatch for this kind of query

This should do:

db.hosts.find({ ip : "127.0.0.1"}, { "services.port_info.product" : "ssh" });

$elemMatch is required if you want to match multiple criteria inside the array object, for instance "find all where port is 9000 and protocol is UDP". That would be unsupported with your data structure. I'm not sure why port_info is an array of objects (maybe for uncertain situtations where a port could belong to two different services?) - if it were a single object, even the $elemMatch would be supported.

Also, keep in mind that such a query will always return the entire object.



来源:https://stackoverflow.com/questions/19432909/mongodb-embed-structure-updating-and-searching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!