node-ottoman icon indicating copy to clipboard operation
node-ottoman copied to clipboard

Query Builder Question

Open AV25242 opened this issue 3 years ago • 5 comments

How to query a field inside array sub-document using ottoman query builder? How to add Collection name and scope name to query builder?`

import { Schema, Query, getDefaultInstance } from "ottoman";

const  TestSchema = new Schema({
block1:{
    field1:{type: String, required: true},
    field2:{type: String, required: true}
},
block2:[{
    field3:{type: String, required: true},
    field4:{type: String, required: true}
}]
})

const ottoman = getDefaultInstance();
const query = new Query({}, 'bucketName.scopeName.collectionName');
const where_exp = {block2[{field3}]:{$eq: 'xyz'}};
const result = query
  .select()
  .where(where_exp)
  .build();
console.log(result);

Source : forum post - https://forums.couchbase.com/t/how-to-query-a-field-inside-array-sub-document-using-ottoman-query-builder-how-to-add-collection-name-and-scope-name-to-query-builder/32978

AV25242 avatar Mar 05 '22 07:03 AV25242

Hello @Vigneshwaran_Rengana to add the fully qualified namespace you are correct use the qualifier like you have mentioned, if your keyspace has special characters than escape the name using the ticks

for instance

const query = new Query({}, 'bucketName.scopeName.collectionName');

@gsi-alejandro can you please assist ?

AV25242 avatar Mar 05 '22 07:03 AV25242

hi @AV25242, @Vigneshwaran_Rengana

To query a nested object you can type the path to it as the object key. e.g.

const where_exp = {"block2.field3": {$eq: "xyz"}};

it will produce this valid N1QL query: SELECT * FROM `bucketName`.`scopeName`.`collectionName` WHERE block2.field3="xyz"

retrieving documents where nested property field3 equal to "xyz"

gsi-alejandro avatar Mar 07 '22 18:03 gsi-alejandro

@gsi-alejandro I think the question is not simply about nested object what if the object is an array ? so in the example block2 is an array ?

block2:[{ field3:{type: String, required: true}, field4:{type: String, required: true} }] })

AV25242 avatar Mar 07 '22 18:03 AV25242

To query into array values use this way:

const where_exp = {
      $any: {
          $expr: [{ b: { $in: 'block2' } }],
          $satisfies: { 'b.field3': {$eq: "xyz"} },
      }
  };

this will produce this valid N1Ql query SELECT * FROM `travel-sample`.`inventory`.`hotel` WHERE ANY b IN block2 SATISFIES b.field3="xyz" END

gsi-alejandro avatar Mar 07 '22 18:03 gsi-alejandro

Thanks

AV25242 avatar Mar 07 '22 18:03 AV25242