json – Apply filters to NoSQL query in MongoDB

Question:

I am working on a project that uses a NoSQL database and I would like to know how to perform a query to filter on the source field of the following dataset:

{
    "_id" : ObjectId("55f9ba45647ba23c39207e9d"),
    "ident" : "66198708-5c99-11e5-824f-00f489953837",
    "timestamp" : ISODate("2015-09-16T18:51:49.681Z"),
    "normalized" : true,
    "payload" : {
        "pattern" : "head",
        "time" : "2015-09-16 15:52:07",
        "filename" : null,
        "source" : [
            "192.168.100.107",
            915
        ],
        "request_raw" : "HEAD / HTTP/1.1\r\nConnection: close\r\nHost: 192.168.100.109\r\nUser-Agent: Mozilla/5.0 (compatible; Nmap Scripting Engine; http://nmap.org/book/nse.html)",
        "request_url" : "/"
    },
    "channel" : "glastopf.events"
}

It is worth clarifying, that I have very little experience in this type of database, the database server is MongoDB v2.6.11

Answer:

If you mean to query from the MongoDB console, you can try the following (I'm using version v3.2 ) using the array operator $all :

db.nombrecoleccion.find({
    'payload.source': {
        $all: ["192.168.100.107", 915]
    }
})

What $all is get the documents where the field value is an array containing the specified elements.

More examples:

  • Find the first element of the array :

     db.nombrecoleccion.find({ 'payload.source.0': "192.168.100.107" })
  • Find the second element and make it greater than 900 :

     db.nombrecoleccion.find({ 'payload.source.1': {$gt: 900} })
  • Search by mixing the two previous conditions:

     db.nombrecoleccion.find({ 'payload.source.0': "192.168.100.107", 'payload.source.1': {$gt: 900} })
  • Find where the first element equals any of the values ​​in an array (using the $in operator):

     db.nombrecoleccion.find({ 'payload.source.0': { $in: [ "192.168.100.105", "192.168.100.107", "192.168.100.109" ] } })

You can check other operators for array in Query Operator Array

Scroll to Top