How can I ensure a complete sub document match in Couchbase?

Below are some sample records stored in couchbase:

{
  a: "iama",
  b: {
    c: "iamc",
    d: "iamd",
  },
  f: "iamf"
  // ... other properties that are not relevant

}

{
  a: "iama",
  b: {
    c: "iamc",
    d: "iamd"
  },
  f: "iamnotf"
  // ... other properties that are not relevant

}

I need to retrieve records where the entire object of b matches, without knowing the exact contents of b.

I am using ottomanjs and have attempted the following code. However, I believe it is not very elegant.

    const arr = [];
    Object.keys(b).forEach((key) => {
      const k = `b.${key}`;
      arr.push({ [k]: b[key] });
    });

    model.find({ $and: arr });

In the example above, the generated filter looks like this:

{
  "$and": [
    {
      "b.c": "iamc"
    },
    {
      "b.d": "iamd"
    }
  ]
}

This filter will be converted into an N1QL query like so:

SELECT * FROM `table` WHERE ( b.c="iamc" AND b.d="iamd") AND _type="model..."

This method only covers the scenario where every property of b is not a nested object. To handle nested objects, a recursive function could be implemented for constructing the filter.

Another approach could involve processing everything in memory by comparing

JSON.stringify(b1) == JSON.stringfy(b2)
or using _.isEqual(b1, b2)

I suspect that my current solution may not be the most efficient. Any advice or alternative approaches?


**other info

If I require all records to have a unique b field, I could use the stringified version of b as the document key. This way, searching for b would simply involve looking up the document id. While ottoman does not support this feature, it can be accomplished with the couchbase sdk.

Answer №1

Simply use the comparison WHERE b1 = b2. This will perform a Json comparison on field names, values (including data type), array positions, and recursively nested information. The encode_json() function is used for stringification.

In the example below, one document matches while the other does not:

SELECT t 
FROM [{ "a": "iama", 
        "b":  { "c": "iamc", "d": "iamd" },
        "b1": { "c": "iamc", "d": "iamd" } }, 
      { "a": "iama", 
        "b":  { "c": "iamc", "d": "iamd" }, 
        "b1": { "c1": "iamc", "d": "iamd" } }
      ] AS t 
WHERE t.b = t.b1;

{
    "results": [
    {
        "t": {
            "a": "iama",
            "b": {
                "c": "iamc",
                "d": "iamd"
            },
            "b1": {
                "c": "iamc",
                "d": "iamd"
            }
        }
    }
    ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Batch requesting in Typescript with web3 is an efficient way to improve

When attempting to send a batch request of transactions to my contract from web3, I encountered an issue with typing in the .request method. My contract's methods are defined as NonPayableTransactionObject<void> using Typechain, and it seems tha ...

Guide to Angular 6 Reactive Forms: Automatically filling one text field when another input is selected

I'm currently learning Angular 6 and exploring reactive forms. I want to set up a feature where selecting an option in one field will automatically populate another field. The objective is to have the coefficient input update based on the number sele ...

Converting ASP .Net Core Dto's and Controllers into TypeScript classes and interfaces

My concept involves incorporating two key elements: Converting C# Dto's (Data-transfer-objects) into TypeScript interfaces to ensure synchronization between client-side models and server-side. Transforming ASP .Net Core controller endpoints into Typ ...

The error message TS2322 occurs due to the inability to assign the type 'Observable<{}[]>' to 'Observable<Archive[][]>'

While upgrading from Angular 5.2.11 to 7.3.9, I encountered a types issue that was not present in the previous version of Angular. After fixing the import for forkJoin, the code snippet below now throws an error: ERROR in src/app/reports/report-measureme ...

Spying on an Angular service with additional parameters present

Is there a way to monitor and imitate a service using another service parameter? For instance, the new Authservice includes this parameter: export class AuthService{ constructor(public serviceAbcd: ServiceAbcd) {} This serves as an illustration withou ...

Error in Next.js: "export" token not recognized as expected

My journey started with NextJS, but before that I was heavily using React. I am currently running my app on Docker (node:18-alpine) which may or may not make a difference. I have an API module that I created earlier and published as an NPM package. I inst ...

The modal in Angular15 will automatically show the date decremented by 1 day whenever it is displayed

Every time I open the date field in a modal, it decrements by one day. Here is the associated typescript file: dob!: DatePipe; rescueDate!: string; dateAdded!: string; openEditPetMenu(template: TemplateRef<any>, petId: number, name: string, ...

Tips for storing information in a JSON document?

I'm looking to save JSON data as a file with the extension .json by converting an object into a string using JSON.stringify This is what my code currently looks like: const jsonObject: object = { 'countryName': 'Switzerland&apos ...

Dynamic type inference in Typescript allows for automatically deducing the data type

interface TableProps { headers: { text: string; value: string; }[]; onClickRow: (item: unknown) => void; api: { url: string; }; } const Table: React.FC<TableProps> = ({headers, onClickRow, api}) => { ...

"Utilizing Postgresql with TypeORM for filtering many-to-many relationships

I have two entities that are connected with a ManyToMany relationship: // Branch entity @ManyToMany( (type) => User, (e) => e.branches ) users: User[]; // User entity @ManyToMany( (type) => Branch, (e) ...

Sorting Dates in Angular 4 Using an Array

I am struggling with sorting an array of Dates in Angular 4. My goal is to arrange my Customer array based on the value of releaseDate. This is what I currently have: Inside the customer.component.ts file : sort() { this.customers.sort((a: Customer, b ...

JSON Object Key passed as a parameter in a function

While I have seen a similar question before, I am still unsure how to apply the solution in my specific case. I am working with a function that returns a stringified JSON object, but I need to modify one of the keys using a parameter within the function. ...

What data structure is used to store HTML elements in TypeScript?

Currently, I am dealing with a typescript variable that holds the outcome of a query on the DOM: let games = document.getElementsByTagname("game"); My uncertainty lies in identifying the appropriate type for the resulting array. Should I expect an array ...

Tips for managing onChange events in TypeScript

I'm still learning Typescript and I have a question regarding handling the onChange event in a TextField component when using Typescript. Can you provide guidance on how to approach this? I currently have a function called handleChangeDate(e: React. ...

Creating a number of arrays based on the row of a .CSV file can be accomplished in Angular by utilizing the

Implementing an Angular template to read .CSV files and generate a table involves creating two separate files: one for the header and another for the table content. For the header CSV file: header.csv https://i.stack.imgur.com/ojMo6.png For the table da ...

Exploring the power of EJS with conditional logic

Can someone help me figure out why EJS is not evaluating to the else branch in my code? I'm using EJS version 3.1.5 with express version 4.17.1 and typescript. ReferenceError: /home/pauld/tscript/dist/views/index.ejs:12 10| </head> 11| & ...

Angular Material Table displaying empty data fields

I'm struggling to populate data using an angular material table. Here is the component: export class CertificateTableComponent { dataSource: MatTableDataSource<any>; //certificates: ValueEntity[] = []; data: CertificateRow[] = []; colu ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

Checking for undefined based on certain conditions

When looking at the following code snippet type stringUndefined = "string" | undefined; type What<T> = T extends undefined ? "true" : "false"; const no : What<stringUndefined> = ""; The value of ' ...

What is the process for importing a submodule from a private package?

I'm currently working on a private npm package in TypeScript that needs to be reused in multiple TS projects. To streamline this process, I created and published the @myorg/core package, containing enums and types that are shared across different repo ...