1

I have the following code in my Atlas trigger function :

  const existings = await test_collection.find().toArray();
  var ids = [];
  
  for (let i = 0; i < existings.length; i++) {
    ids.push(existings[i]._id);
  }

  console.log("Existing ids : ", ids);
  const value = await user_collection.find({"_id": {$nin: ids}}).sort({quantity: -1}).limit(1);
  console.log("Value is : ", JSON.stringify(value));

The logs are showing this :

Logs:
[
  "Existing ids :  vfLGh8QVOsbmz1,F7Mqe1YwH5fsV83",
  "Value is :  {}",
]

The python equivalent that is actually working :

 def test(self):
        test = self.db.test.find()
        ids = []
        for t in test:
            ids.append(t["_id"])
        print(f"Existing ids : {ids}")
        value = self.db.users.find({"_id": {"$nin": ids}}).sort("quantity", pymongo.DESCENDING).limit(1)
        print(f"Value is : {value[0]}")

And python logs :

Existing ids : ['vfLGh8QVOsbmz1', 'F7Mqe1YwH5fsV83']
Value is : Value is : {'_id': '6GzgNoZFR2H7hfdzI3', 'username': 'test3'}

I have tried without the sort operator to be sure the issue would come from $nin, i have the same empty output without the sort

5
  • Is there another process inserting documents? Why do you expect more "_id"s after retrieving all docs and then searching for extra "_id"s? Commented Aug 20, 2022 at 19:44
  • Thanks for your comment, please have a look at the collections they are different. I fetch all documents (2) from a collection test, then i want to take a user from the users collection which was not already in test collection. Commented Aug 20, 2022 at 20:05
  • 1
    Ah, I see now - my oversight. Yeah, the difference is curious. Out of curiosity, if you replace $nin with $in, do you get the expected results? Commented Aug 20, 2022 at 20:27
  • Well it's a good question ! i have tried and the result is also empty... which makes me think there is really something wrong with my syntax perhaps... It can't a bug in both operators. Commented Aug 20, 2022 at 20:38
  • I'm a javascript noob so I don't think I'll be of much help. I guess you'll need to do some debugging. Commented Aug 20, 2022 at 20:42

1 Answer 1

1

You need to add the toArray() method after the limit(1) to convert the value and to not get a cursor.

This look like :

const value = await user_collection.find({"_id": {$nin: ids}}).sort({quantity: -1}).limit(1).toArray();

and your value const should have the result.

Sign up to request clarification or add additional context in comments.

Comments

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.