这是我从xml转换为json格式的nmap扫描的摘录:
{
"nmaprun": {
"@scanner": "nmap",
"@args": "nmap -T4 -F -sV -O -n --exclude 192.168.10.1 -oX nmap-00:90:a9:0e:87:21.xml 192.168.10.1/24",
"@start": "1470812419",
"@startstr": "Wed Aug 10 00:00:19 2016",
"@version": "7.12",
"@xmloutputversion": "1.04",
"scaninfo": {
"@type": "syn",
"@protocol": "tcp",
"@numservices": "100",
"host": {
"@starttime": "1470812419",
"@endtime": "1470812462",
"status": {
"@state": "up",
"@reason": "arp-response",
"@reason_ttl": "0"
},
"address": [
{
"@addr": "192.168.1.123",
"@addrtype": "ipv4"
},
{
"@addr": "18:B4:30:4C:94:1B",
"@addrtype": "mac"
}
]
}
以下查询的返回尝试查找并投影MAC地址+地址类型,其中包含额外字段
db.nmaps.find({"nmaprun.host.address.@addr":"18:B4:30:4C:94:1B","nmaprun.host.address.@addrtype":"mac"},{"nmaprun.host.address.@addrtype":1, "nmaprun.host.address.@addr":1}).pretty()
返回与查询参数不匹配的额外字段。具体来说,ipv4和ip地址也会被返回。不知道为什么会这样。
返回查询:
{
"_id" : ObjectId("57acb4c35e18500dc5f4d7d8"),
"nmaprun" : {
"host" : {
"address" : [
{
"@addr" : "",
"@addrtype" : "ipv4"
},
{
"@addr" : "18:B4:30:4C:94:1B",
"@addrtype" : "mac"
}
]
}
}
}
答案 0 :(得分:1)
获得两个数组元素的原因是整个文档被认为与您提供的查找条件匹配,并且您的投影中没有任何内容可以将结果限制为仅匹配的数组元素。
更改所需内容以获得预期结果的一种简单方法是在投影中使用位置$运算符(https://docs.mongodb.com/manual/reference/operator/projection/positional/):
db.nmaps.find({"nmaprun.host.address.@addr":"18:B4:30:4C:94:1B","nmaprun.host.address.@addrtype":"mac"},{"nmaprun.host.address.$":1}).pretty()
另一种方法是使用聚合:
db.nmaps.aggregate([
{
$unwind: "$nmaprun.host.address"
},
{
$match:{
"nmaprun.host.address.@addr":"18:B4:30:4C:94:1B",
"nmaprun.host.address.@addrtype":"mac"
}
},
{
$project:{
"nmaprun.host.address.@addrtype":1,
"nmaprun.host.address.@addr":1
}
}
])