Stern
Stern

Reputation: 61

how can i add conditional fields on output-query of mongodb?

My schema is shown below :

var productSchema = new Schema({
    name : String,
    likes : [{
        user_id : Schema.Types.ObjectId,
        date : Date
    }]
});

Assume that I have this collection

{ name : A, likes : [ {user_id : id1, date : blahblah}, {user_id : id2, date : balh}] }

{ name : B, likes : [ {user_id : id1, date : blahblah}] }

{ name : C }

then I want to show, following kinda of output by querying it

(with user_id = id1){ name : A, like : 1}, { name : B, like : 1}, { name : C, like : 0}

(with user_id = id2){ name : A, like : 1}, { name : B, like : 0}, { name : C, like : 0}

So to say, i want to add new field, called 'like' here.

If the user_id exists in array(likes), like is 1, if not, should be zero.

Can i make this happen?

Upvotes: 1

Views: 110

Answers (2)

randunel
randunel

Reputation: 8945

For your Schema, you should perform the following query:

db.collection.find({ likes: { $elemMatch: { user_id: idX }}});

This way, you will get the products with entries for idX userId. All the other ones don't have a userId in the likes array. With this method, you need to add the output with 1 and the others not in the output with 0.

You didn't mention if a userId may have different entries within the same array, because that changes the problem.

Upvotes: 0

Andrew Orsich
Andrew Orsich

Reputation: 53685

The best way to do it is to have collection of liked products ids in user schema. So when someone like product you have to add userId to the product collection and product id to the user collection. This is common way to implement many to many relations in mongodb. Optional, to increase read performance, you could denormalize product name into user:

var userSchema = new Schema({
    name : String,
    likedProducts : [{
        _id : Schema.Types.ObjectId,
        productName: String
    }]
});

But keep in the mind that denormalization add overhead to write operations. On product name update you will update it in users collection as well.

Upvotes: 1

Related Questions