1

I want to fetch data from the MongoDB. Since I am new into Node.Js and MongoDB. I am not able to get the data.

I am passing primary category and secondary category to an API where I want to match the primary and secondary category with the array field "category" which is having two indexes 0 and 1 ,in the 0 index primary category is there and in the 1 index secondary categories are there separated by ~ .

Below is my code to get the data according to primary category but I want to get the data by matching the primary and secondary category from the db.

ProductModel
.find({ category : { $all : [req.body.primary] }})
.select('id link brand title description category image images in_stock price sale_price merchant_number part_number GroupID status promotion attributes tags currency updated -_id')
.then((productList) => {
  response.status = 200;
  response.msg = 'Success';
  response.count = productList.length;
  response.data = productList
  res.json(response);
})
.catch(() => {
  response.status = 500;
  response.msg = 'connection error';
  response.data = [];
  res.json(response);
});

Sample Doc :

Database structure screenshot

So I wanted to input something like ['Health','women'] & get docs where all of these elements in category array exists, kind of regex search on array elements.

Can Someone help me out to get the data from the db.

9
  • what do you mean by this :: but i want to get the data by matching the primary and secondary category from the db ? Do you want records where you've both primary & secondary ? Then that case you can just do .find({ category : { $all : [req.body.primary, req.body.secondary] }}) Commented Feb 26, 2020 at 15:35
  • Have you seen my database structure in the image provided.inside the category field there are two indexes 0 and 1 . I want to match 0 index value as "Health" and 1 index value as "women",but in the 1 indexes values are ~ seperated how to match these and get the data Commented Feb 26, 2020 at 17:56
  • Ok, so you wanted to match send ['Health', 'women'] to category & get the doc out ?? If that's what you need then your question is unclear !! Can you confirm on that.. Commented Feb 26, 2020 at 18:02
  • Yes. In the category field 1st index values are considered as my secondary categories in that sample data image provided the 1st index values are "tes~men~women" so here "tes" is a secondary category ,"men" is another secondary category and "women" is another secondary category. I am not able to match the value and get the result Commented Feb 26, 2020 at 18:07
  • 1
    You can try this :: db.getCollection('AddToSet').find({$and: [{category : {$in : [/women/]}}, {category : {$in : ['Health']}}]}) Commented Feb 26, 2020 at 18:11

1 Answer 1

2

If you've to query with input as ['Health', 'women'] & get the documents which has both listed & also get the documents which has something like this : category : ["Health", "tes~men~women"] then you can try below query :

Query :

db.collection.find({
  $and: [
    {
      category: {
        $in: [
          /\bwomen\b/
        ]
      }
    },
    {
      category: {
        $in: [
          "Health"
        ]
      }
    }
  ]
})

Js Code :

const secondary = req.body.secondary
const primary = req.body.primary
db.collection.find({
    $and: [
        {
            category: {
                $in: [
                    new RegExp(`\\b${secondary}\\b`, 'i')
                ]
            }
        },
        {
            category: {
                $in: [
                    primary
                ]
            }
        }
    ]
})
Sign up to request clarification or add additional context in comments.

8 Comments

In this if i am passing ['Health', 'men'] then also i will get results which includes women also ,since the "women" word ends with "men" so how can i sort this if i pass ['Health', 'men'] it should only return results set of ['Health', 'men']
Basically this is a dynamic process ,the "Health" can be changed to "clothing & accessories " ,"Jewellery & Watches" and so on and the "women" can be changed to "men" ,"boy" and so on. This is for a e-commerce website where user selects a primary category("Health","clothing & accessories " ,"Jewellery & Watches") and secondary category ("men","women","boy") there will be may primary and secondary categories ,so as i said earlier in the category array 0 index is considered as primary category(Health) and 1st index as considered secondary category (men~women~test123)
This is working fine ProductModel.find({$and: [{category : {$in : [/\bmen\b/]}}, {category : {$in : [req.body.primary]}}]}) can you tell me how can i make it dynamic: ProductModel.find({$and: [{category : {$in : [/\breq.body.secondary\b/]}}, {category : {$in : [req.body.primary]}}]})
It is working as expected "[{category : {$in : [/\bmen\b/]}}" but i want to pass the value inside the condition like this [{category : {$in : [/\breq.body.secondary\b/]}
it is working in the expected way ,thank you for helping me out of the box
|

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.