0

Below is couchbase document structure I am working on :

  {
"name":"Harry",
"lastname":"sam",
"supplier_info": {
    "HU": [
      {
        "40383": "Bangalore."
      },{
        "41163": "new."
        }
    ],
"SK": [
      {
        "40383": "DYNAMIT KFT."
      }
    ]
}

Requirement is to get all the documents from my db which has supplier number as "40383" irrespective of country. How can I do that with N1ql queries? (I do not have country info as well)

1 Answer 1

1
SELECT * FROM default WHERE ANY v IN ARRAY_FLATTEN(OBJECT_VALUES(supplier_info),2) SATISFIES "40383" IN OBJECT_NAMES(v) END;

Input data

INSERT INTO default VALUES("kkk01",{ "supplier_info": { "HU": [ { "40383": "Bangalore." },{ "41163": "new." } ], "SK": [ { "40383": "DYNAMIT KFT." } ] }}), VALUES("kkk03",{ "supplier_info": { "HU": [ { "40383": "Bangalore." },{ "41164": "az." } ], "SK": [ { "40385": "DYNAMIT" } ] }});

The following query gives Distinct countries

SELECT DISTINCT country FROM (SELECT RAW ARRAY_FLATTEN(ARRAY ARRAY v.name FOR u IN v.val WHEN "40383" IN OBJECT_NAMES(u) END FOR v IN OBJECT_PAIRS(supplier_info) END,2) FROM default ) AS countries UNNEST countries AS country WHERE country IS NOT MISSING;

Getting supplier name, country, name and lastname for all the records with supplier number 40383.

SELECT q.name, q.lastname, s.country, s.snumber, s.sname FROM (SELECT name, lastname, ARRAY_FLATTEN(ARRAY ARRAY {"country":v.name, "snumber":OBJECT_PAIRS(u)[0].name, "sname":OBJECT_PAIRS(u)[0].val} FOR u IN v.val WHEN "40383" IN OBJECT_NAMES(u) END FOR v IN OBJECT_PAIRS(supplier_info) END,2) AS sinfo FROM default ) AS q UNNEST q.sinfo AS s;
Sign up to request clarification or add additional context in comments.

6 Comments

What if I want to retrieve country(where "40383" exists and supplier name in the query instead of whole document???
SELECT DISTINCT country FROM (SELECT RAW ARRAY_FLATTEN(ARRAY ARRAY v.name FOR u IN v.val WHEN "40383" IN OBJECT_NAMES(u) END FOR v IN OBJECT_PAIRS(supplier_info) END,2) FROM default ) AS countries UNNEST countries AS country WHERE country IS NOT MISSING;
Thanks a lot for the help :)
My requirement is something as below: This is the whole object I have- { "name":"Harry", "lastname":"sam", "supplier_info": { "HU": [ { "40383": "Bangalore." },{ "41163": "new." } ], "SK": [ { "40383": "DYNAMIT KFT." } ] } I want a query to fetch supplier name, country, name and lastname for all the records with supplier number 40383. Thanks in advance.
can you please help
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.