node-ottoman
node-ottoman copied to clipboard
Query Builder Question
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
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 ?
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 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} }] })
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
Thanks