0

Is it possible to query MongoDB for values of a specific field-name disregarding where it's located in the document structure?

For example If I have this document: https://mongoplayground.net/p/ANSezUHhueD

{
  device_name: "host1",
  ip: 192.168.1.10,
  connected_hosts: [
    {
      name: "host2",
      ip: 192.168.1.11
    },
    {
      name: "host2",
      ip: 192.168.1.12
    }        ​
 ​]
}

Can I look for all the fields named "ip" no matter where they are defined, so I get a result that lists all 3 IPs [192.168.1.10, 192.168.1.11, 192.168.1.12]?

In my use case the nested document {name, ip} can appear in additional different other nested documents.

RaamEE
  • 3,017
  • 4
  • 33
  • 53
  • 1
    You may be looking for idea in this [SO answer](https://stackoverflow.com/questions/2997004/using-map-reduce-for-mapping-the-properties-in-a-collection/3011885#3011885). It uses mapReduce and recursion to process nested/array structure. – ray Oct 18 '21 at 02:56
  • Thanks @ray. This gives me a good direction to follow. I still feel that a list of all the attributes of a document should be builtin metadata of the document. Something that can be pulled out in a search. Following your feedback, I think I will map all the document's fields when I insert\update the document and then use this "metadata" to do a search to pull documents that contain fields that are "*.ip" and process them. – RaamEE Oct 18 '21 at 09:53
  • 1
    Thats a good idea. In fact I will suggest you refactor your schema if possible to make the structure less dynamic. It can help with easing the difficulty in composing the queries :) – ray Oct 18 '21 at 10:29

0 Answers0